POJ 1154 LETTERS DFS+回溯

LETTERS
 Time Limit: 1000MS Memory Limit: 10000K

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 6
HFDFFB
AJHGDH
DGAGEH

Sample Output

6
/* Author : yan
* Question : POJ 1154 LETTERS
* Data && Time : Sunday, January 16 2011 09:04 PM
* Compiler : gcc (Ubuntu 4.4.3-4ubuntu5) 4.4.3
*/
#include<stdio.h>
char map[30][30];
int row,col;
int visited[26];
int max=-1;
/*
*做这题的时候,回溯法中应对辅助的全局变量及时作出修改.
*一般的,如果在回溯法中修改了辅助的全局变量,则一定要及时把
*它们恢复原状,即将来的状态不应该修改这些值——至少"看上去没
*有修改",若函数有多个出口,则需要在每个出口处恢复被修改的值.
*/
void DFS(int a,int b,int cnt)//要回溯,
{
if(visited[map[a][b]-'A']) return;
//printf("visited %d %d  %c/n",a,b,map[a][b]);
if(max<cnt) max=cnt;
if(b>0)
{
visited[map[a][b]-'A']=1;
DFS(a,b-1,cnt+1);
visited[map[a][b]-'A']=0;
}
if(b<col-1)
{
visited[map[a][b]-'A']=1;
DFS(a,b+1,cnt+1);
visited[map[a][b]-'A']=0;
}
if(a>0)
{
visited[map[a][b]-'A']=1;
DFS(a-1,b,cnt+1);
visited[map[a][b]-'A']=0;
}
if(a<row-1)
{
visited[map[a][b]-'A']=1;
DFS(a+1,b,cnt+1);
visited[map[a][b]-'A']=0;
}

}
int main()
{
freopen("input","r",stdin);
int i;

scanf("%d %d",&row,&col);
for(i=0;i<row;i++) scanf("%s",map[i]);
DFS(0,0,1);
printf("%d",max);
return 0;
}


• 本文已收录于以下专栏：

举报原因： 您举报文章：POJ 1154 LETTERS DFS+回溯 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)