题意:给出一张n*m的图,找出顺序为DIMA的路径, 可以循环也就是说可以DIMADIMA..... 如果形成回路就Poor Inna!, 如果找不到一组DIMA就Poor Dima!, 如果能找到输出找到DIMA的最大循环次数。
思路:记忆化搜索,判断回路的话直接判断是否访问过就行了
#include<cstring>
#include<cmath>
#include<cstdio>
#include<stack>
#include<algorithm>
using namespace std;
const int qq = 1e3+10;
const int MAXN = 1e9 + 10;
char map[qq][qq];
int vis[qq][qq];
int dp[qq][qq]; //代表从点(i, j)搜索下去能找到DIMA的最大个数、
int dx[]={0 ,0, 1, -1};
int dy[]={1, -1, 0, 0};
char flag[4]={'D', 'I', 'M', 'A'};
int n,m;
int dfs(int x, int y, int cnt){
if(dp[x][y]!=-1) return dp[x][y];
int ans = 0;
int tmp;
for(int i=0; i<4; ++i){
int xx = x+dx[i];
int yy = y+dy[i];
if(map[xx][yy]!=flag[cnt%4]||x<1||x>n||y<1||y>m) continue;
if(vis[xx][yy]) ans = MAXN;
else{
vis[xx][yy] = 1;
tmp = dfs(xx, yy, cnt+1);
vis[xx][yy] = 0;
ans = max(ans, tmp);
}
}
return dp[x][y] = ans+1;
}
int main(){
memset(vis, 0, sizeof(vis));
memset(dp, -1, sizeof(dp));
scanf("%d%d",&n,&m);
for(int i=1; i<=n; ++i)
scanf("%s", map[i]+1);
int ans = 0;
for(int j,i=1; i<=n; ++i){
for(j=1; j<=m; ++j)
if(dp[i][j]==-1&&map[i][j]=='D'){
vis[i][j] = 1;
int x=dfs(i, j, 1);
ans = max(ans, x);
vis[i][j] = 0;
}
}
if(ans/4==0) printf("Poor Dima!\n");
else if(ans>=MAXN) printf("Poor Inna!\n");
else printf("%d\n", ans/4);
return 0;
}