简单搜索题。
注意:回溯时需要减1,否则会WA。
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
const int SIZE = 30;
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
char maze[SIZE][SIZE];
int flag[SIZE];
int ans, n, m, num;
int check(int x, int y)
{
if(x >= 0 && y >= 0 && x < n && y < m) return 1;
else return 0;
}
void dfs(int x, int y)
{
for(int i = 0 ; i < 4; i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
if(check(xx, yy) && !flag[maze[xx][yy]-'A'])
{
flag[maze[xx][yy]-'A'] = 1;
num++;
dfs(xx, yy);
if(ans < num) ans = num;
flag[maze[xx][yy]-'A'] = 0;
num--; //回溯时需要num--;
}
}
}
void init()
{
memset(flag, 0, sizeof(flag));
memset(maze, 0, sizeof(maze));
ans = num = 1;
}
int main()
{
while(~scanf("%d%d", &n, &m))
{
init();
for(int i = 0; i < n; i++) scanf("%s", maze[i]);
flag[maze[0][0]-'A'] = 1; //初始点标记,很重要,调试了N久。
dfs(0, 0);
printf("%d\n", ans);
}
return 0;
}
#include <stdlib.h>
#include <string.h>
using namespace std;
const int SIZE = 30;
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
char maze[SIZE][SIZE];
int flag[SIZE];
int ans, n, m, num;
int check(int x, int y)
{
if(x >= 0 && y >= 0 && x < n && y < m) return 1;
else return 0;
}
void dfs(int x, int y)
{
for(int i = 0 ; i < 4; i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
if(check(xx, yy) && !flag[maze[xx][yy]-'A'])
{
flag[maze[xx][yy]-'A'] = 1;
num++;
dfs(xx, yy);
if(ans < num) ans = num;
flag[maze[xx][yy]-'A'] = 0;
num--; //回溯时需要num--;
}
}
}
void init()
{
memset(flag, 0, sizeof(flag));
memset(maze, 0, sizeof(maze));
ans = num = 1;
}
int main()
{
while(~scanf("%d%d", &n, &m))
{
init();
for(int i = 0; i < n; i++) scanf("%s", maze[i]);
flag[maze[0][0]-'A'] = 1; //初始点标记,很重要,调试了N久。
dfs(0, 0);
printf("%d\n", ans);
}
return 0;
}
浙公网安备 33010602011771号