题意:R行S列的格子中填满大写字母,问从左上角的格子开始走,每次只能或上或下或左或右移动一格且那个格子的字母不能走过,最多能走几步。
题目链接:http://poj.org/problem?id=1154
——>>直接dfs。
#include <cstdio> #include <cstring> using namespace std; const int maxn = 20 + 10; int R, S, ret; int dx[] = {-1, 1, 0, 0}; int dy[] = { 0, 0, -1, 1}; char MAP[maxn][maxn]; bool vis[30]; bool is_end(int x, int y) //是否不可再走 { bool ok = 1; for(int i = 0; i < 4; i++) { int newx = x + dx[i]; int newy = y + dy[i]; if(newx >= 0 && newx < R && newy >= 0 && newy < S && !vis[MAP[newx][newy]-'A']) { ok = 0; break; } } return ok; } void dfs(int x, int y, int cur) //搜索 { if(is_end(x, y)) { ret = cur > ret ? cur : ret; return; } for(int i = 0; i < 4; i++) { int newx = x + dx[i]; int newy = y + dy[i]; if(newx >= 0 && newx < R && newy >= 0 && newy < S && !vis[MAP[newx][newy]-'A']) { vis[MAP[newx][newy]-'A'] = 1; dfs(newx, newy, cur+1); vis[MAP[newx][newy]-'A'] = 0; } } } int main() { int i, j; while(scanf("%d%d", &R, &S) == 2) { for(i = 0; i < R; i++) { getchar(); for(j = 0; j < S; j++) MAP[i][j] = getchar(); } ret = 1; memset(vis, 0, sizeof(vis)); vis[MAP[0][0]-'A'] = 1; //注意! dfs(0, 0, 1); printf("%d\n", ret); } return 0; }