Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 9162 | Accepted: 3973 |
Description
Input
Output
Sample Input
2 8 8 ######## #......# #.####.# #.####.# #.####.# #.####.# #...#..# #S#E#### 9 5 ######### #.#.#.#.# S.......E #.#.#.#.# #########
Sample Output
37 5 5 17 17 9
Source
#include <stdio.h> #include <string.h> char str[50][50] ; int n , m ; int map_str[50][50] ; int dfs_s[4][2] = { {1,0},{-1,0},{0,1},{0,-1} } ; /* 0 3 1 2*/ struct node { int x, y ; int temp ; } p[1000000]; void dfs1(int x,int y,int temp,int dir) { if(str[x][y] == 'E') { printf("%d ", temp); return ; } int i = dir - 1 ; if(i == -1) i = 3 ; while( 1 ) { if(i == 0 && x-1 >= 0 && str[x-1][y] != '#') { dfs1(x-1,y,temp+1,i); break; } else if(i == 1 && y+1 < m && str[x][y+1] != '#') { dfs1(x,y+1,temp+1,i); break; } else if(i == 2 && x+1 < n && str[x+1][y] != '#') { dfs1(x+1,y,temp+1,i); break; } else if(i == 3 && y-1 >= 0 && str[x][y-1] != '#') { dfs1(x,y-1,temp+1,i); break; } i++ ; if(i == 4) i = 0 ; } return ; } void dfs2(int x,int y,int temp,int dir) { if(str[x][y] == 'E') { printf("%d ", temp); return ; } int i = dir + 1 ; if(i == 4) i = 0 ; while( 1 ) { if(i == 0 && x-1 >= 0 && str[x-1][y] != '#') { dfs2(x-1,y,temp+1,i); break; } else if(i == 1 && y+1 < m && str[x][y+1] != '#') { dfs2(x,y+1,temp+1,i); break; } else if(i == 2 && x+1 < n && str[x+1][y] != '#') { dfs2(x+1,y,temp+1,i); break; } else if(i == 3 && y-1 >= 0 && str[x][y-1] != '#') { dfs2(x,y-1,temp+1,i); break; } i-- ; if(i == -1) i = 3 ; } return ; } void bfs(int x,int y,int temp) { memset(map_str,0,sizeof(map_str) ) ; p[0].x = x ; p[0].y = y ; p[0].temp = temp ; map_str[x][y] = 1 ; int low = 0 , top = 1 , i ; while(low < top) { node k = p[low++] ; if(str[k.x][k.y] == 'E') { printf("%d\n", k.temp); break; } for(i = 0 ; i < 4 ; i++) { int u = k.x + dfs_s[i][0] ; int v = k.y + dfs_s[i][1] ; if( u >= 0 && u < n && v >= 0 && v < m && map_str[u][v] == 0 && str[u][v] != '#') { p[top].x = u ; p[top].y = v ; p[top++].temp = k.temp + 1 ; map_str[u][v] = 1 ; } } } return ; } int main() { int t , i , j , x , y ; scanf("%d", &t); while(t--) { scanf("%d %d", &m, &n) ; for(i = 0 ; i < n ; i++) scanf("%s", str[i]); for(i = 0 ; i < n ; i++) { for(j = 0 ; j < m ; j++) { if(str[i][j] == 'S') { x = i ; y = j ; break; } } if(j != m) break; } if(x == 0) { dfs1(x,y,1,2); dfs2(x,y,1,2); } else if(x == n-1) { dfs1(x,y,1,0); dfs2(x,y,1,0); } else if(y == 0) { dfs1(x,y,1,1); dfs2(x,y,1,1); } else if(y == m-1) { dfs1(x,y,1,3); dfs2(x,y,1,3); } bfs(x,y,1) ; } return 0; }