1. 程式人生 > >廣度優先搜尋的學習

廣度優先搜尋的學習

同樣也是用一個迷宮的例子

#include<iostream>
using namespace std;
struct note
{
	int x;//橫座標
	int y;//縱座標
	int s;//步數
};
int main() {
	struct note que[2501];//設地圖50X50,所以佇列2500
	int a[51][51] = { 0 };//地圖
	int book[51][51] = { 0 };//標記哪些點走過了
	int next[4][2] = {
		{0,1},//右
		{1,0},//下
		{0,-1},//左
		{-1,0}//上
	};
	int head, tail,flag;
	int next_x, next_y;
	int n,m,start_x,start_y,p,q;
	cout << "輸入行和列" << endl;
	cin >> n >> m;
	cout << "輸入迷宮" << endl;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
			cin >> a[i][j];
	cout << "輸入起點座標" << endl;
	cin >> start_x >> start_y;
	cout << "輸入終點座標" << endl;
	cin >> p >> q;
	head = 1;//佇列初始化
	tail = 1;
	que[tail].x = start_x;
	que[tail].y = start_y;
	que[tail].s = 0;
	tail++;
	book[start_x][start_y] = 1;
	flag = 0;//標記是否到達,1為到達
	while (head<tail)
	{
		for (int i = 0; i < 4; i++) {
			next_x = que[head].x + next[i][0];//順時針方向,上下左右
			next_y = que[head].y + next[i][1];
			if (next_x<1 || next_x>n || next_y<1 || next_y>m)//判斷越界
				continue;
			if (a[next_x][next_y] == 0 && book[next_x][next_y] == 0) {//判斷是否可走
				book[next_x][next_y] = 1;//寬度遍歷只要入隊一次,所以不需要將book還原
				que[tail].x = next_x;
				que[tail].y = next_y;
				que[tail].s = que[head].s + 1;
				tail++;
			}
			if (next_x == p&&next_y == q) {//判斷到達
				flag = 1;
				break;
			}
		}
		if (flag == 1)
			break;
		head++;//當一個點擴充套件結束後,head++才能對下一個點擴充套件
	}
	cout << que[tail - 1].s << endl;//tail是指向隊尾的下一個位置,所以要減一
	return 0;
}