在一个二维表中搜特定序列的串。采用记忆化的搜索。
dp[x][y]表示x,y能达到的最大深度,如果每次搜的时候能搜到原来的点,那么就是无穷的。如果dp[x][y]的深度大于4,说明是存在特定串的。
AC代码:
#include <cstdio> #include <cstring> #include <vector> using namespace std; #define max(a,b) ((a) > (b)) ? (a) : (b) const int MAX_NUMBER = 1003; int n, m; char next[] = "DIMA"; char maps[MAX_NUMBER][MAX_NUMBER]; int steps[][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; int vis[MAX_NUMBER][MAX_NUMBER]; int dp[MAX_NUMBER][MAX_NUMBER]; int find, infi, max_ans; void dfs(int cnt_x, int cnt_y, char cnt_char) { if (dp[cnt_x][cnt_y] != -1) { return ; } if (cnt_char == 'A') { dp[cnt_x][cnt_y] = 1; find = 1; } int next_char; for (int i = 0; i < 4; i++) { if (next[i] == cnt_char) { next_char = i; break; } } for (int i = 0; i < 4 && !infi; i++) { int next_x = cnt_x + steps[i][0]; int next_y = cnt_y + steps[i][1]; if (maps[next_x][next_y] == next[(next_char + 1) % 4]) { if (vis[next_x][next_y]) { infi = 1; } else { vis[next_x][next_y] = 1; dfs(next_x, next_y, next[(next_char + 1) % 4]); dp[cnt_x][cnt_y] = max(dp[cnt_x][cnt_y], dp[next_x][next_y] + 1); vis[next_x][next_y] = 0; } } } } int main() { scanf("%d%d", &n, &m); memset(maps, 0, sizeof(maps)); for (int i = 1; i <= n; i++) { scanf("%s", maps[i] + 1); } memset(vis, 0, sizeof(vis)); memset(dp, -1, sizeof(dp)); find = infi = max_ans = 0; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (maps[i][j] == 'D' && !vis[i][j]) { vis[i][j] = 1; dfs(i, j, 'D'); if (max_ans < dp[i][j] / 4) { max_ans = dp[i][j] / 4; } vis[i][j] = 0; } } } if (!find) { printf("Poor Dima!\n"); } else { if (infi) { printf("Poor Inna!\n"); } else { printf("%d\n", max_ans); } } return 0; }