记忆化搜索

# include <stdio.h>
# include <string.h>


# define REP(i,a,b) for(i = a ; i<= b ; i++)


typedef long long ll ;
ll MOD = 0x7fffffff ;
int n ;
char graph[1010][1010] ;
int vis[1010][1010] ;
ll dp[1010][1010] ;
int q[1010*1010][2] ;
int tab[4][2] = {{0,-1},{0,1},{-1,0},{1,0}} ;


void bfs()
{
int i, x, y, xx, yy ;
int front = 0, rear = 1 ;
if (graph[1][1] == '#') return ;
memset (vis, 0, sizeof(vis)) ;
vis[1][1] = 1 ;
q[0][0] = q[0][1] = 1 ;
while (front != rear)
{
x = q[front][0], y = q[front][1] ;
front ++ ;
if (x == n && y == n) return ;

for(i = 0 ;i < 4 ; i++)
{
xx = x + tab[i][0] ;
yy = y + tab[i][1] ;
if (xx < 1 || xx > n) continue ;
if (yy < 1 || yy > n) continue ;
if (vis[xx][yy] == 1) continue ;
if (graph[xx][yy] == '#') continue ;
vis[xx][yy] = 1 ;
q[rear][0] = xx, q[rear][1] = yy ;
rear++ ;
}
}
}


int dfs(int x, int y)
{
long long ans = 0 ;
if (x < 1 || x > n || y < 1 || y > n) return 0 ;
if (dp[x][y] != -1) return dp[x][y] ;
if (graph[x][y] == '#')
return dp[x][y] = 0 ;

if (x+1 <= n) ans += dfs (x+1, y) ;
if (y+1 <= n) ans += dfs (x, y+1) ;
return dp[x][y] = ans%MOD ;
}


int main ()
{
int i, j ;
while (~scanf ("%d", &n))
{
REP(i,1,n) scanf ("%s", &graph[i][1]) ;
if (graph[1][1] == '#'){
puts ("INCONCEIVABLE") ;
continue ;
}
memset (dp, -1, sizeof(dp)) ;
dp[n][n] = 1 ;
dfs (1,1) ;
bfs () ;
if (dp[1][1] != 0) printf ("%lld\n", dp[1][1]) ;
else if (vis[n][n] != 0) printf ("THE GAME IS A LIE\n") ;
else printf ("INCONCEIVABLE\n") ;
}
return 0 ;
}

 

posted @ 2012-04-07 23:35  朝圣の路  阅读(282)  评论(0编辑  收藏  举报