http://codeforces.com/problemset/problem/374/C
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
const int inf = 0x3fffffff;
const int maxx = 1010;
int m,n,t,vis[maxx][maxx],dp[maxx][maxx];
char map[maxx][maxx];
int d[4][2] = {-1,0,1,0,0,-1,0,1};
char check(char ch)
{
if(ch == 'D') return 'I';
if(ch == 'I') return 'M';
if(ch == 'M') return 'A';
if(ch == 'A') return 'D';
}
struct A
{
int x,y;
}c[maxx*maxx];
int dfs(int x,int y,char ch)
{
//cout<<x<<" "<<y<<" "<<ch<<endl;
int tx,ty,ans = 0;
if(dp[x][y] != -1) return dp[x][y];
for(int i = 0; i < 4; i++)
{
tx = x+d[i][0], ty = y+d[i][1];
if(tx <1 || ty <1 || tx >m || ty>n || check(ch) != map[tx][ty]) continue;
if(vis[tx][ty]) ans = inf;
else
{
vis[tx][ty] = 1;
t = dfs(tx,ty,map[tx][ty]);
vis[tx][ty] = 0;
ans = max(ans,t);
}
}
dp[x][y] = ans+1;
return dp[x][y];
}
int main()
{
int i,j,k =1;
int num = 0;
cin>>m>>n;
for(i = 1; i <= m; i++)
for(j = 1; j <= n; j++)
{
cin>>map[i][j];
if(map[i][j] == 'D') c[k].x = i,c[k++].y = j;
}
memset(dp,-1,sizeof(dp));
memset(vis,0,sizeof(vis));
for(i = 1; i < k; i++)
{
vis[c[i].x][c[i].y] = 1;
t = dfs(c[i].x,c[i].y,'D');
vis[c[i].x][c[i].y] = 0;
num = max(num,t/4);
}
//cout<<num<<endl;
if(num > inf/4) cout<<"Poor Inna!"<<endl;
else if(num == 0) cout<<"Poor Dima!"<<endl;
else cout<<num<<endl;
return 0;
}