先声明,这是我的练习笔记
BFS——广度优先遍历(相当于流水漫过大地,一点变面,各路兵马齐头并进,一路蔓延。找最短路径就是“大汉朝兵分多路,追击外族,走一步,分一只,走一步分一支,最终霍去病那一只兵马首先追到敌军,封狼居胥,然后所有兵马就全部班师回朝”)嘿哈!
#include<iostream>
using namespace std;
struct note {
int x;
int y;
int f;
int s;
};
int main() {
struct note que[2501];//用来储存过程中变量,用“模拟链表”理解那就太通畅了,唯一不同的是,BFS是记录上一条地址,同时一条地址可以被多个子点记录。模拟链表是记录一条地址。仅此而已
int a[51][51] = { 0 }, book[51][51] = { 0 }, m, n, startx, starty, endtx, endty, flag = 0;
cin >> m >> n;
int i, j;
for ( i = 1; i <= m; i++) {
for (j = 1; j <= n; j++)
cin >> a[i][j];
//a[i][j] = i+j;
}
cin >> startx >> starty >> endtx >> endty;
int next[4][2] = {{0,1} ,{1,0} , {0, -1},{-1,0}};
int head=1, tail=2,tx,ty;
que[head].x = startx;
que[head].y = starty;
que[head].f = 0;
que[head].s = 0;
book[startx][starty] = 1;
while (head < tail)
{
for (int k = 0; k < 4; k++) {
tx = que[head].x + next[k][0];
ty = que[head].y + next[k][1];
if (tx<1 || tx > m ||ty < 1 || ty > n) {
continue;
}
if (a[tx][ty] == 0 && book[tx][ty] == 0)
{
que[tail].x = tx;
que[tail].y = ty;
que[tail].f = head;
que[tail].s = que[head].s + 1;
tail++;//延申
book[tx][ty] = 1;
}
if (tx == endtx && ty == endty) {
flag = 1;
break;
}
}
if (flag == 1)
break;
head++;//重点
}
int str[2501][2] = { NULL };
if (flag == 1) {
cout << "最短步数为 " << que[tail - 1].s << endl;
cout << "路径为: "<<endl;
i =1 ;
tail--;
while (que[tail].s != 0) {
str[i][0] = que[tail].x;
str[i][1]=que[tail].y;
tail = que[tail].f;
i++;
}
i--;
cout << "(" << startx << "," << starty << ")"<<endl;
while(i>0) {
cout << "(" << str[i][0] << "," << str[i][1] << ")"<<endl;
i--;
}
}
else
cout << "没有路径或程序错误"<<endl;
system("PAUSE");
return 0;
}
//5 4
//0 0 1 0
//0 0 0 0
//0 0 1 0
//0 1 0 0
//0 0 0 1
//1 1 4 1
最后是测试用,
还可以做海岛扩张,全图扫描等问题,这种情况就是一支等到while(head<tail)循环完即可。