代码:
#include <cstdio>
#include <iostream>
using namespace std;
int r, s, ans, max1;
char a[27][27];
bool vis[27][27];
int b[207], dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
void dfs (int, int);
int main()
{
scanf ("%d%d", &r, &s);
for (int i = 1; i <= r; i++)
{
for (int j = 1; j <= s; j++)
cin >> a[i][j];
}
dfs (1, 1);
printf ("%d", max1);
return 0;
}
void dfs (int x, int y)
{
if (b[a[x][y]] > 0)
{
if (ans > max1)
max1 = ans;
return;
}
else
{
for (int i = 0; i <= 3; i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
if (xx >= 1 && xx <= r && yy >= 1 && yy <= s && vis[xx][yy] == 0 && b[a[xx][yy]] <= 0)
{
ans++;
b[a[xx][yy]] ++;
vis[xx][yy] = 1;
dfs (xx, yy);
b[a[xx][yy]] --;
vis[xx][yy] = 0;
}
}
}
}
在线等,求助!