walk the maze
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 94 Solved: 83
[ Submit ][ Status ][ Web Board ]
Description
X is in a maze of size M*N, and the obstacles in the maze are impassable. In the maze, use S to represent X, E to represent exit, # to represent obstacles, and * to represent traversable roads. X can only walk in four directions: up, down, left, and right, and each step can only take one unit of length. Now, given M, N, and the appearance of the maze, how many times do you need to change the walking direction when solving X to the exit? If X cannot reach the exit, output -1, otherwise output the minimum number of changes required, X will try to take the route with fewer changes in direction, as long as the two adjacent walking directions are different, it will change the direction once. (1<=M,N<=100)
Input
then input the M*N maze, the maze elements only contain S, E, *, # four characters.
Input ends in file (EOF).
Output
Sample Input
5 5
S****
####*
*****
*####
****E
Sample Output
4
HINT
Because the obstacle (#) cannot pass, so S can only reach E through *, and at least 4 turns are required
//The method of wide search in the maze is similar to deep search, except that wide search is faster than deep search.
d is the direction array subscript changes direction, d is different from i, so sum++, in short, it is a very basic search question
# include <iostream> # include <cstring> # include <queue> using namespace std; char str[105][105]; int sx, sy, px, py; struct node { int x, y, d; int sum }; int f[105][105]; int n , m; queue<struct node> q; int flag = 0; int t = 0x3f3f3f3f; int dis[][2] = {0, 1, 0, -1, 1, 0, -1, 0}; void bfs(int x, int y) { struct node temp,head; temp.x = x; temp.y = y; temp.d = -1; temp.sum = 0; q.push(temp); while(!q.empty()) { temp = q.front(); head = temp; // cout << "head.x =" << head.x << " head.y = " << head.y << " head.d = " << head.d << " head.sum = " << head.sum << endl; q.pop(); if(temp.x == px && temp.y == py) { if(t > temp.sum) { t = temp.sum; } flag = 1; // cout << temp.sum << endl; } for(int i = 0; i < 4; i++) { head.x = temp.x + dis[i][0]; head.y = temp.y + dis[i][1]; if(head.x < 0 || head.x >= n || head.y < 0 || head.y >= m|| str[head.x][head.y] != '*' ) { continue; } if(!f[head.x][head.y]) { f[head.x][head.y] = 1; if(head.d == -1) { head.d = i; head.sum = temp.sum; q.push(head); } else { if(head.d != i) { head.d = i; head.sum = temp.sum + 1; q.push(head); } else { q.push(head); } } } } } return ; } int main(int argc, char *argv[]) { while(cin >> n >> m) { t = 0x3f3f3f3f; flag = 0; memset(f, 0,sizeof(f)); memset(str, 0, sizeof(str)); for(int i = 0; i < n; i++) { cin >> str[i]; } for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(str[i][j] == 'S') { sx = i; sy = j; str[i][j] = '*'; } if(str[i][j] == 'E') { px = i; py = j; str[i][j] = '*'; } } } bfs (sx, sy); if(!flag) { cout << -1 << endl; } else { cout << t << endl; } } return 0; }