- describe
-
When you're standing in a maze, you tend to get disoriented by the intricate paths, and if you can get your hands on a map of the maze, things get really easy.
Suppose you have obtained a drawing of an n*m maze, please find the shortest path from the starting point to the exit. - enter
-
The first line is two integers n and m (1<=n, m<=100), which represent the number of rows and columns of the maze.
The next n lines, each with a string of length m, represent the layout of the entire maze. The characters '.' represent open spaces, '#' represent walls, 'S' represent starting points, and 'T' represent exits. - output
- Output the minimum number of steps required to travel from the starting point to the exit.
- DFS
-
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cctype> #include <algorithm> using namespace std; int n,m,walk[200][200],sx,sy,ex,ey,ans=0x3f3f3f3f; char s[200][200]; int row[4]={-1,0,1,0}; int col[4]={0,1,0,-1}; void DFS(int x,int y,int sum) { if(x==ex&&y==ey) { if(sum<ans) ans=sum; return; } for(int i=0;i<=3;i++) { int xx=x+row[i]; int yy=y+col[i]; if(xx>=0&&xx<m&&yy>=0&&yy<n&&walk[xx][yy]>sum+1&&s[xx][yy]!='#') { walk[xx][yy]=sum+1; DFS(xx,yy,sum+1); } } return; } intmain () { cin>>m>>n; memset(walk,0x3f,sizeof(walk)); for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { cin>>s[i][j]; if(s[i][j]=='S') { sx = i; sy = j; } if(s[i][j]=='T') { ex=i;ey=j; } } } walk [sx] [sy] == 0 ; DFS (sx, sy, 0 ); cout<<ans<<endl; return 0; }
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <algorithm> #include <queue> using namespace std; const int maxn=100; struct node{ int x,y; int step; }S,T,Node; int n,m; char maze[maxn][maxn]; bool inq[maxn][maxn]; int X[4]={0,0,1,-1}; int Y[4]={1,-1,0,0}; bool test(int x,int y) { if(x>=n||x<0||y>=m||y<0) return false; if(maze[x][y]=='#'||inq[x][y]==true) return false; return true; } int BFS() { queue<node>q; q.push(S); while(!q.empty()) { node top=q.front(); q.pop(); if(top.x==T.x&&top.y==T.y) { return top.step; } for(int i=0;i<4;i++) { int newX=top.x+X[i]; int newY=top.y+Y[i]; if(test(newX,newY)) { Node.x = newX; Node.y = newY; Node.step=top.step+1; q.push(Node); inq [newX] [newY] = true ; } } } return -1; } intmain () { scanf("%d%d",&n,&m); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { cin>>maze[i][j]; } } for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(maze[i][j]=='S') { S.x=i; Sy = j; } if(maze[i][j]=='T') { T.x=i; Ty = j; } } } S.step=0; printf("%d\n",BFS()); return 0; }
6264: Out of the Maze (DFS and BFS)
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=325897487&siteId=291194637
Ranking