- 题目链接http://bailian.openjudge.cn/practice/1154/
- 总时间限制: 1000ms 内存限制: 65536kB
- 描述
- 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. - 输入
- 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. - 输出
- The first and only line of the output should contain the maximal number of position in the board the figure can visit.
- 样例输入
-
3 6 HFDFFB AJHGDH DGAGEH
- 样例输出
-
6
- 来源
- Croatia OI 2002 Regional Competition - Juniors
算法:深搜
代码一:
1 #include<iostream> 2 using namespace std; 3 int bb[26]={0},s,r,sum=1,s1=1; 4 char aa[25][25]; 5 int dir[4][2]={-1,0,1,0,0,-1,0,1}; 6 void dfs(int a,int b) 7 { 8 int a1,b1; 9 if(s1>sum) sum=s1; //更新最大数值 10 for(int i=0;i<4;i++) 11 { 12 a1=a+dir[i][0]; //用bb数组记录访问过的字母 13 b1=b+dir[i][1]; 14 if(a1>=0&&a1<s&&b1>=0&&b1<r&&!bb[aa[a1][b1]-'A']) 15 { 16 s1++; 17 bb[aa[a1][b1]-'A']=1; //如果在这条单线上没有记录改字母被访问过,则总数++; 18 dfs(a1,b1); //第一个字母总要被访问,所以不用回溯; 19 bb[aa[a1][b1]-'A']=0; //回溯反标记 20 s1--; //临时记录恢复 21 } 22 } 23 } 24 int main() 25 { 26 cin>>s>>r; 27 for(int i=0;i<s;i++) 28 for(int j=0;j<r;j++) 29 cin>>aa[i][j]; 30 bb[aa[0][0]-'A']=1; 31 dfs(0,0); 32 cout<<sum<<endl; 33 return 0; 34 }