describe:
Given the maze, the starting point and the ending point, find the shortest distance from the starting point to the ending point, (you can only walk up and down, left and right, one grid distance 1)
DFS
#include <iostream> #include <algorithm> using namespace std; //Maze, x,y start from (1,1), int minn = 0x3f3f3f3f; int next[4][2] = {{0,1},{1,0},{0,-1},{-1,0}}; //The direction coordinates are right, down, left, up int a[50][50]; int book[50][50]; int n,m; int sx, sy, ex, ey; void DFS(int x,int y,int step) //The current position, the number of steps taken { if(x == ex && y == ey) // if it has arrived, compare the number of steps { if(step < minn) minn = step; return; } for(int i = 0;i < 4;i++) //There are four directions to choose from each step { int nx = x + next[i][0]; int ny = y + next[i][1]; //The coordinates of the next step. if(nx <1 || nx > n || ny < 1 || ny > m) // if out of bounds continue; if(a[nx][ny] == 0 && book[nx][ny] == 0) //if the point is not an obstacle and is not in the path. { book[nx][ny] = 1; //mark this point DFS(nx,ny,step + 1); //Start trying the next point book[nx][ny] = 0; //The end of the attempt, cancel the mark of this point, the following is the next direction } } return; } intmain() { cin>>n>>m; for(int i = 1;i <= n;i ++) { for(int j = 1;j <= m;j ++) { cin>>a[i][j]; } } cin>>sx>>sy>>ex>>ey; DFS (sx, sy, 0); cout<<minn<<endl; return 0; }
BFS
#include <iostream> #include <algorithm> #include <queue> using namespace std; struct Note { int x; //abscissa int y; // ordinate int s; // number of steps }; Rating N; queue<Note> q; int a[51][51]; //Store the map int book[51][51] = {0}; int next[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}}; int n,m; int sx, sy, ex, ey; int flag; intmain() { int nx,ny;//The coordinates of the next point scanf("%d %d",&n,&m); for(int i = 1;i <= n;i ++) { for(int j = 1;j <= m;j ++) scanf("%d",&a[i][j]); } scanf("%d %d %d %d",&sx,&sy,&ex,&ey); N.x = sx; The = and; N.s = 0; q.push(N);//Add the starting point to the queue first book[sx][sy] = 1; //The starting point has been visited flag = 0; // mark whether to reach the target point while(!q.empty()) //When the queue is not empty { for(int i = 0;i < 3;i++) //four directions { N.x = q.front().x + next[i][0]; Ny = q.front().y + next[i][1]; //The coordinates of the new point // Determine whether it is out of bounds if(N.x < 1 || N.x > n || N.y < 1 || N.y > n) continue; / / Determine whether it is an obstacle or has been in the path if(a[N.x][N.y] == 0 && book[N.x][N.y] == 0) { book[N.x][N.y] = 1; // new point is added to the queue N.s = q.front().s + 1; q.push(N); } if(N.x == ex && N.y == ey) { flag = 1; break; } } if(flag == 1) break; q.pop(); //The four directions of a point have been judged, delete the team leader, and then expand } printf("%d\n",q.back().s); return 0; }