描述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
简单的dfs
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
char matrix[25][25];
int m,n;
int maxx=0;
int flag[200];
int step[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
void dfs(int x,int y,int dis)
{
int k=0;
for(int i=0;i<4;i++)
{
int tempx=x+step[i][0];
int tempy=y+step[i][1];
int index=matrix[tempx][tempy];
if(tempx>=0&&tempx<m&&tempy>=0&&tempy<n&&flag[index]!=1)
{
k=1;
flag[index]=1;
dfs(tempx,tempy,dis+1);
flag[index]=0;
}
}
if(k==0&&dis>maxx)
maxx=dis;
}
int main()
{
memset(flag,0,sizeof(flag));
cin>>m>>n;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin>>matrix[i][j];
}
}
int index=matrix[0][0];
flag[index]=1;
dfs(0,0,1);
cout<<maxx;
return 0;
}