http://poj.org/problem?id=1154
Description
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 following R lines contain S characters each. Each line represents one row in the board.
Output
Sample Input
3 6
HFDFFB
AJHGDH
DGAGEH
Sample Output
6
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
这道题不是多组输入,只是单组输入,如果写成多组输入后就会出现Output Limit Exceeded,这应该算是一篇比较简单dfs,代码中的一大亮点是map标记数组的应用,很精奥。
#include<stdio.h>
#include<string.h>
#define NN 30
#define MAX(a,b) (a)>(b)?(a):(b)
int m,n,ans;
char huiyao[NN][NN];
int ope[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int map[27];
void dfs(int x,int y,int step)
{
int xl,yl,l;
ans=MAX(ans,step);
map[huiyao[x][y]-'A']=0;
for(l=0;l<4;l++)
{
xl=x+ope[l][0];
yl=y+ope[l][1];
if(xl<0||yl<0||xl>=m||yl>=n)
continue;
if(map[huiyao[xl][yl]-'A']==0)
continue;
map[huiyao[xl][yl]-'A']=0;
dfs(xl,yl,step+1);
map[huiyao[xl][yl]-'A']=1;
}
}
int main()
{
int i,j,k;
scanf("%d%d",&m,&n);
getchar();
memset(map,0,sizeof(map));
for(i=0;i<m;i++)
scanf("%s",huiyao[i]);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
map[huiyao[i][j]-'A']=1;
}
}
ans=1;
dfs(0,0,1);
printf("%d\n",ans);
/*for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%c",huiyao[i][j]);
}
printf("\n");
}*/
return 0;
}