poj 1154 LETTERS

#include <iostream>
#include <string>
using namespace std;
const int MAX = 25;
char matrix[MAX][MAX];
int r, s, ans;
bool vis[30];

void init()
{
     int i, j;
     for (i = 0; i < r; i++){
         getchar();
         for (j = 0; j < s; j++){
             scanf("%c", &matrix[i][j]);
         }
     }
     
     return ;
}


void DFS(int x, int y, int cnt)
{
     if (x+1 < r && !vis[matrix[x+1][y] - 'A']){
         vis[matrix[x+1][y] - 'A'] = 1;
         cnt++;
         DFS(x+1, y, cnt);
         cnt--;
         vis[matrix[x+1][y] - 'A'] = 0;
     } 
     if (y+1 < s && !vis[matrix[x][y+1] - 'A']){
         vis[matrix[x][y+1] - 'A'] = 1;
         cnt++;
         DFS(x, y+1, cnt);
         cnt--;
         vis[matrix[x][y+1] - 'A'] = 0;
     }  
     if (x-1 >= 0 && !vis[matrix[x-1][y] - 'A']){
         vis[matrix[x-1][y] - 'A'] = 1;
         cnt++;
         DFS(x-1, y, cnt);
         cnt--;
         vis[matrix[x-1][y] - 'A'] = 0;
     }  
     if (y-1 >= 0 && !vis[matrix[x][y-1] - 'A']){
         vis[matrix[x][y-1] - 'A'] = 1;
         cnt++;
         DFS(x, y-1, cnt);
         cnt--;
         vis[matrix[x][y-1] - 'A'] = 0;
     } 
     if (cnt > ans){
         ans = cnt; 
         return ;
     } 
}


int main()
{
    while (scanf("%d%d", &r, &s) != EOF){
            memset(vis, 0, sizeof(vis));
            ans = 0;
            init();
            vis[matrix[0][0] - 'A'] = 1;
            DFS(0, 0, 1);  
            cout << ans << endl; 
    }
    
    system("pause");
}


/*
3 6
HFDFFB
AJHGDH
DGAGEH
5 5
ABAAA
BCAAA
CDERT
SDFGH
LLLLL
*/

你可能感兴趣的:(c,System,include,Matrix)