Out of the maze
Source: C ++ Informatics Yitong
Description
When you stand in a maze, you are often disoriented by intricate roads. If you can get a map of the maze, things will become very simple.
Assuming you have obtained a drawing of an n * m maze, please find the shortest path from the starting point to the exit.
Input
The first row is two integers n and m (1 <= n, m <= 100), which represents the number of rows and columns of the maze.
The next n lines, each line is a string of length m, indicating the layout of the entire maze. The character '.' Means open space, '#' means wall, 'S' means starting point, and 'T' means exit.
Output
The output requires a minimum number of steps from the starting point to the exit.
Sample input
3 3
S #T
. # .
. . .
[Note: There is no space in the sample]
Sample output
6
This question is still
search for
Cough cough cough
Back to topic
Let ’s look at the sample first. The
red ones are walls (traps)
Yellow is the way
Decree to
void dfs(int x,int y)
{
if(x==fx&&y==fy)//判断是否到达终点
{
return;
}
else
{
for(int i=0;i<4;i++)//上下左右四个方向
{
int nx=x+dx[i];
int ny=y+dy[i];
if(nx>=0 && nx<=n && ny>=0 && ny<=m && tmp[nx][ny]==0 && b[nx][ny]==0 && (a[nx][ny]=='.' || a[nx][ny]=='T'))//判断是否出界 & 是否访问过 & 不是陷阱
{
ans++; //累加
tmp[nx][ny]=1;
dfs(x+dx[i],y+dy[i]);
}
}
}
}
Because the search (blog) I wrote last time did not determine if I was out of bounds
But it ’s also right. Do n’t doubt my level.
Because this time I have been debugging for a long time and found this question must judge whether it is out of bounds
and so
Very different from the if judgment of the previous blog
Previous blog:
if(tmp[nx][ny]==0&&a[nx][ny]==1)//是否走过 & 是否为陷阱
{
tmp[x][y]=1;
dfs(x+dx[i],y+dy[i]);
tmp[x][y]=0;
}
This time:
if(nx>=0 && nx<=n && ny>=0 && ny<=m && tmp[nx][ny]==0 && b[nx][ny]==0 && (a[nx][ny]=='.' || a[nx][ny]=='T'))//判断是否出界 & 是否访问过 & 不是陷阱
{
ans++; //累加
tmp[nx][ny]=1;
dfs(x+dx[i],y+dy[i]);
}
The emperor arrived
#include<iostream>
using namespace std;
char a[10][10];
int b[10][10];
bool tmp[10][10];
int dx[4]={0,0,1,-1};
int dy[4]={-1,1,0,0};
int ans,fx,fy,sx,sy,T,n,m,l,r;
void dfs(int x,int y)
{
if(x==fx&&y==fy)//判断是否到达终点
{
return;
}
else
{
for(int i=0;i<4;i++)//上下左右四个方向
{
int nx=x+dx[i];
int ny=y+dy[i];
if(nx>=0 && nx<=n && ny>=0 && ny<=m && tmp[nx][ny]==0 && b[nx][ny]==0 && (a[nx][ny]=='.' || a[nx][ny]=='T'))//判断是否出界 & 是否访问过 & 不是陷阱
{
ans++; //累加
tmp[nx][ny]=1;
dfs(x+dx[i],y+dy[i]);
}
}
}
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>a[i][j];
if(a[i][j]=='S')
{
sx=i;
sy=j;
}
else if(a[i][j]=='T')
{
fx=i;
fy=j;
}
else if(a[i][j]=='#') b[i][j]=1;
}
}
tmp[sx][sy]=1;
dfs(sx,sy);
cout<<ans;
return 0;
}