C++搜索与回溯算法之LETTERS(字母)

来源:互联网 发布:射频版图设计软件 编辑:程序博客网 时间:2024/04/19 23:14


LETTERS(字母)

Description

A single-player game is played on a rectangular board divided in R rows and C columns. There is a single uppercase letter (A-Z) written in every position in the board.
Before the begging of the game there is a figure in the upper-left corner of the board (first row, first column). In every move, a player can move the figure to the one of the adjacent positions (up, down,left or right). Only constraint is that a figure cannot visit a position marked with the same letter twice.
The goal of the game is to play as many moves as possible.
Write a program that will calculate the maximal number of positions in the board the figure can visit in a single game.

Input

The first line of the input contains two integers R and C, separated by a single blank character, 1 <= R, S <= 20.
The following R lines contain S characters each. Each line represents one row in the board.

Output

The first and only line of the output should contain the maximal number of position in the board the figure can visit.

Sample Input

3 6HFDFFBAJHGDHDGAGEH

Sample Output

6


题目大意

描述:

给出一个R*S的大写字母矩阵,一开始的位置是左上角,你可以向上下左右四个方向移动,并且不能移向曾经经过的字母。问最多可以经过几个字母。
输入:
第一行,输入字母矩阵行数R
和列数S,1<=R,S<=20。
接着输入
RS列字母矩阵。
输出:
最多能走过的不同字母的个数。

题目分析

这道题跟迷宫问题差不多,只是不能经过同样的“位置”。

代码如下

#include<cstdio>int r,c,sum=1,maxword=1,wayr[4]={1,-1,0,0},wayc[4]={0,0,1,-1};char map[21][21];bool mark[360];bool check(int x,int y){if(x>=0&&y>=0&&x<r&&y<c&&!mark[map[x][y]]) return 1;return 0;}void dfs(int m,int n){for(int i=0;i<4;i++)if(check(m+wayr[i],n+wayc[i])){mark[map[m+wayr[i]][n+wayc[i]]]=1;sum++;dfs(m+wayr[i],n+wayc[i]);if(sum>maxword) maxword=sum;sum--;mark[map[m+wayr[i]][n+wayc[i]]]=0;}}int main(){scanf("%d%d",&r,&c);for(int i=0;i<r;i++)scanf("%s",map[i]);mark[map[0][0]]=1;dfs(0,0);printf("%d",maxword);}