http://acm.pku.edu.cn/JudgeOnline/problem?id=1154
第一题不是用暴力过的哦,嘿嘿
//深度优先搜索
#include <iostream>
using namespace std;
struct dfs
{
int row, col;
int dire;
}path[100000];//为什么用*path会发生运行错误,不能执行path[i]的访问.
int out(char p[21][21], int row, int col)
{
int dire;
int result;
int top;
int t;
int record[26] = {0};
int i, j, g, h;
int incr[4][2] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0}};
top = 1;
dire = 0;
i = j = 0;
path[top].row = i;
path[top].col = j;
/**//***************************************
* 课本的这里是path[top].dire = dire;即=0;但是path[top]中表示的dire是当前top点在前一顶点的方位.
* 故在题目中当top = 1时path[top].dire表示它相对于top = 0时的方位,当path[top]改变时说明已经返回到了top = 0 处.
* 即top = 1遍历完毕;但当path[top].dire = 0;此时+1 = 1 而不是= 4 所以函数并没有中断循环.
* 此时top-- ,所以top = 0;会出现path[0]指向第一定点,而path[1]则指向了第二个定点而产生错误.
***************************************/
path[top].dire = 3; //path[top].dire = dire;
record[p[i][j] - 'A']++;
result = 0;
while(top > 0 || dire < 4)
{
if(dire < 4)
{
g = i + incr[dire][0];
h = j + incr[dire][1];
t = p[g][h] - 'A';
if(g >= 0&&g < row&& h >= 0&& h < col &&record[t] == 0)
// if(record[t] == 0)刚开始因这样而出错
{
record[t]++;
top++;
path[top].row = g;
path[top].col = h;
path[top].dire = dire;
i = g; j = h; dire = 0;
}
else{
dire++;
}
}
else{
/**//*
cout << top << endl;
for(i = 1; i <= top; i++)
cout << path[i].row << " " << path[i].col << endl;
*/
dire = path[top].dire + 1;
t = p[path[top].row][path[top].col] - 'A';
record[t]--;
if(result < top){
result = top;
}
top--;
if(top > 0){
i = path[top].row;
j = path[top].col;
}
}
}
return result;
}
int main()
{
int i;
int row, col;
int result;
char p[21][21];
cin >> row >> col;
for(i = 0; i < row; i++)
cin >> p[i];
result = out(p, row, col);
cout << result << endl;
return 0;
}