练习笔记 BFS——广度优先遍历(寻找最短路径)

先声明,这是我的练习笔记
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)循环完即可。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值