《算法笔记》P280
这一题值得珍藏!!
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
const int maxn = 100;
struct node{
int x,y;//位置{x,y}
int step;//step为从起点S到大该位置的最少步数(层数)
}S,T,Node;//分别为起点、终点、临时节点
int n,m;
char maze[maxn][maxn];
bool inq[maxn][maxn] = {false};//记录位置{x,y}是否已入过队
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] == '*') return false;
if(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++){//循环4次,得到4个相邻位置
int newX = top.x + X[i];
int newY = top.y + Y[i];
if(test(newX,newY)){//新位置有效,启动Node(临时节点)
Node.x = newX,Node.y = newY;
Node.step = top.step + 1;
q.push(Node);
inq[newX][newY] = true;//设置位置(newX,newY)已入过队
}
}
}
return -1;//无法到达终点T时返回-1
}
int main(){
scanf("%d%d",&n,&m);//行数、列数
for(int i = 0;i <n;i++){
getchar();
for(int j = 0;j <m;j++){
maze[i][j] = getchar();
}
maze[i][m+1] = '\0';
}
scanf("%d%d%d%d",&S.x,&S.y,&T.x,&T.y);//起点与终点的坐标
S.step = 0;//初始化起点层数为0
printf("%d\n",BFS());
return 0;
}