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;
}