求迷宫中入口和出口距离
给定一个n*m数组,数组中存放字符。*代表墙壁,. 代表空地,S代表起点,T代表终点。每次只能向上下左右四个方向移动一个位置。求S到T的要走多少步。
思路:BFS。从起点S开始计数遍历层数,每经过一层计数加1。
注意点:参考
求矩阵中块数
代码:
#include<bits\stdc++.h>
using namespace std;
const int N = 100;
const int dx[] = {0,0,-1,1};
const int dy[] = {-1,1,0,0};
struct Matrix{
char position;
bool visited;
}matrix[N][N];
struct Node{
int x;
int y;
int step;//step表示从S到该位置最少多少步
};
Node start,end;//起点和终点
int row,col;//迷宫行数列数
void BFS(){
queue<Node> q;
q.push(start);
while(!q.empty()){
Node top = q.front();
matrix[top.x][top.y].visited = true;
if(matrix[top.x][top.y].position == 'T'){
end.x = top.x;
end.y = top.y;
end.step = top.step;
return;
}
q.pop();
for(int i = 0;i < 4;i ++){
int new_x = top.x + dx[i];
int new_y = top.y + dy[i];
if(new_x >= 0 && new_y >= 0 && new_x < row && new_y < col){
if(matrix[new_x][new_y].position != '*' && matrix[new_x][new_y].visited == false){
Node temp;
temp.x = new_x;
temp.y = new_y;
temp.step = top.step + 1;
q.push(temp);
}
}
}
}
}
int main(){
cin>>row>>col;
for(int i = 0;i < row;i ++){
for(int j = 0;j < col;j ++){
cin>>matrix[i][j].position;
matrix[i][j].visited = false;
if(matrix[i][j].position == 'S'){
start.x = i;
start.y = j;
start.step = 0;
}
}
}
BFS();
cout<<end.step<<endl;
return 0;
}