天天看點

bfs搜尋(+回溯法)例題剖析(一)

前言

  • dfs搜尋(+回溯法)例題剖析(一)
  • dfs搜尋(+回溯法)例題剖析(二)
  • bfs搜尋(+回溯法)例題剖析(一)

例題剖析系列

bfs模闆: (大家看情況更改,我隻是列舉了一個輪廓)

#include <queue>

bool vis[][]; // 若題目沒有提供地圖則不用,可以直接用maze的值充當vis
int maze[][];
int dir[][2] = {{1, 0}, {0, -1}, {0, 1}, {-1, 0}};

strcut Node{
	// ...
	node(status...) { // 構造函數
		// ... = ...;
	}
}

// 判斷位址是否合法 
bool checkOk(int x, int y) {  // 這裡我假設從1開始
	return x <= maxX && x >= 1 && y <= maxY && y >= 1;
}

void bfs(status...) {
	queue<node> q;
	q.push({status...});
	while(!q.empty) {
		node now = q.front();
		q.pop();
		
		vis[now.x][now.y] = true;
		// 結束條件
		if (endstatus) {
			// ...
		}
		for (int i = 0; i <= 4; i++) {
			int nx = now.x + dir[i][0];
			int ny = now.y + dir[i][1];
			
			// 不是障礙物 && 沒有通路過 && 位置合法不越界 
			if (maze[nx][ny] == 0 && !vis[nx][ny] && checkOk(nx, ny)) {
				q.push({status...});
			}
		}
	}
}
           

題目

迷宮

【問題描述】

下圖給出了一個迷宮的平面圖,其中标記為 1 的為障礙,标記為 0 的為可 以通行的地方。

010000
000100
001001
110000
           

迷宮的入口為左上角,出口為右下角,在迷宮中,隻能從一個位置走到這 個它的上、下、左、右四個方向之一。 對于上面的迷宮,從入口開始,可以按DRRURRDDDR 的順序通過迷宮, 一共 10 步。其中 D、U、L、R 分别表示向下、向上、向左、向右走。 對于下面這個更複雜的迷宮(30 行 50 列),請找出一種通過迷宮的方式, 其使用的步數最少,在步數最少的前提下,請找出字典序最小的一個作為答案。 請注意在字典序中D<L<R<U。

【題目給出的資料】

01010101001011001001010110010110100100001000101010
00001000100000101010010000100000001001100110100101
01111011010010001000001101001011100011000000010000
01000000001010100011010000101000001010101011001011
00011111000000101000010010100010100000101100000000
11001000110101000010101100011010011010101011110111
00011011010101001001001010000001000101001110000000
10100000101000100110101010111110011000010000111010
00111000001010100001100010000001000101001100001001
11000110100001110010001001010101010101010001101000
00010000100100000101001010101110100010101010000101
11100100101001001000010000010101010100100100010100
00000010000000101011001111010001100000101010100011
10101010011100001000011000010110011110110100001000
10101010100001101010100101000010100000111011101001
10000000101100010000101100101101001011100000000100
10101001000000010100100001000100000100011110101001
00101001010101101001010100011010101101110000110101
11001010000100001100000010100101000001000111000010
00001000110000110101101000000100101001001000011101
10100101000101000000001110110010110101101010100001
00101000010000110101010000100010001001000100010101
10100001000110010001000010101001010101011111010010
00000100101000000110010100101001000001000000000010
11010000001001110111001001000011101001011011101000
00000110100010001000100000001000011101000000110011
10101000101000100010001111100010101001010000001000
10000010100101001010110000000100101010001011101000
00111100001000010000000110111000000001000000001011
10000001100111010111010001000110111010101101111000
           

思路: BFS

題解參考: https://www.cnblogs.com/woxiaosade/p/10592061.html

下面代碼對原文代碼進行了優化(非時間複雜度):

#include <iostream>
#include <string>
#include <queue>

using namespace std;

int maze[35][55];
int dir[][2] = {{1, 0}, {0, -1}, {0, 1}, {-1, 0}};
char d[4] = {'D', 'L', 'R', 'U'};
bool vis[35][55];
int maxX = 30, maxY = 50;

struct node {
	int x;
	int y;
	string route;
	// 說實話,這道題不需要你算出走了多少步(step),不過為了更好地面對以後的題目,有可能會問到
	int step;
	node(int xx, int yy, string ss, int tt) {
		x = xx;
		y = yy;
		route = ss;
		step = tt;
	}
};

// 判斷位址是否合法 
bool checkOk(int x, int y) {
	return x <= maxX && x >= 1 && y <= maxY && y >= 1;
}

void bfs(int x, int y, string s, int num) {
	queue<node> q;
	q.push({x, y, s, num});
	while(!q.empty()) {
		node now = q.front();
		q.pop();
		
		vis[now.x][now.y] = true;
		
		// 到達終點 
		if (now.x == maxX && now.y == maxY) {
			cout << "the step you walk: " << now.step << endl;
			cout << now.route << endl;
			break;
		}
		
		for (int i = 0; i < 4; i++) {
			int nx = now.x + dir[i][0];
			int ny = now.y + dir[i][1];
			
			// 不是障礙物 && 沒有通路過 && 位置合法不越界 
			if (maze[nx][ny] == 0 && !vis[nx][ny] && checkOk(nx, ny)) {
				q.push({nx, ny, now.route + d[i], now.step + 1});
			}
		} 
	}
}

int main() {
	char temp;
	for (int i = 1; i <= maxX; i++){
		for (int j = 1; j <= maxY; j++){
			cin >> temp;
			maze[i][j] = temp -'0';
		}
	}
	bfs(1, 1, "", 0);
}

           
bfs搜尋(+回溯法)例題剖析(一)

在練習的時候可以使用: 線上文本差異比較工具 比較答案是否正确。

【答案】DDDDRRURRRRRRDRRRRDDDLDDRDDDDDDDDDDDDRDDRRRURRUURRDDDDRDRRRRRRDRRURRDDDRRRRUURUUUUUUULULLUUUURRRRUULLLUUUULLUUULUURRURRURURRRDDRRRRRDDRRDDLLLDDRRDDRDDLDDDLLDDLLLDLDDDLDDRRRRRRRRRDDDDDDRR

這裡插一嘴,當時考慮了一下深搜, 但是深搜容易誤入歧途, 是以隻能算比較小規模的。

dfs + 回溯找到所有解:

#include <iostream>
#include <string>

using namespace std;

int maze[35][55];
int dir[][2] = {{1, 0}, {0, -1}, {0, 1}, {-1, 0}};
char d[4] = {'D', 'L', 'R', 'U'};
bool vis[35][55];
int maxX = 4, maxY = 6;

// 判斷位址是否合法 
bool checkOk(int x, int y) {
	if (x <= maxX && x >= 1 && y <= maxY && y >= 1) {
		return true;
	}
	return false;
}


void dfs(int x, int y, string s, int num) {
	if (x == maxX && y == maxY) {
		cout << "the step you walk: " << num << endl;
		cout << s << endl;
		return;
	} 
	
	for (int i = 0; i < 4; i++) {
		int nx = x + dir[i][0];
		int ny = y + dir[i][1];
		if (!vis[nx][ny] && maze[nx][ny] == 0 && checkOk(nx, ny)) {
//			cout << nx << " " << ny << endl;
			vis[nx][ny] = true;
			dfs(nx, ny, s + d[i], num + 1);
			vis[nx][ny] = false; // 回溯 
		}
	}
}

int main() {
	char temp;
	for (int i = 1; i <= maxX; i++){
		for (int j = 1; j <= maxY; j++){
			cin >> temp;
			maze[i][j] = temp -'0';
		}
	}
	vis[1][1] = true;
	dfs(1, 1, "", 0);
}
           
bfs搜尋(+回溯法)例題剖析(一)

由于dfs容易誤入歧途,找到的路不保證是最近的, 這裡把回溯的部分注釋掉,重新跑一下30 * 50 的題目

#include <iostream>
#include <string>

using namespace std;

int maze[35][55];
int dir[][2] = {{1, 0}, {0, -1}, {0, 1}, {-1, 0}};
char d[4] = {'D', 'L', 'R', 'U'};
bool vis[35][55];
int maxX = 4, maxY = 6;

// 判斷位址是否合法 
bool checkOk(int x, int y) {
	if (x <= maxX && x >= 1 && y <= maxY && y >= 1) {
		return true;
	}
	return false;
}


void dfs(int x, int y, string s, int num) {
	if (x == maxX && y == maxY) {
		cout << "the step you walk: " << num << endl;
		cout << s << endl;
		return;
	} 
	
	for (int i = 0; i < 4; i++) {
		int nx = x + dir[i][0];
		int ny = y + dir[i][1];
		if (!vis[nx][ny] && maze[nx][ny] == 0 && checkOk(nx, ny)) {
//			cout << nx << " " << ny << endl;
			vis[nx][ny] = true;
			dfs(nx, ny, s + d[i], num + 1);
			// vis[nx][ny] = false; // 回溯 
		}
	}
}

int main() {
	char temp;
	for (int i = 1; i <= maxX; i++){
		for (int j = 1; j <= maxY; j++){
			cin >> temp;
			maze[i][j] = temp -'0';
		}
	}
	vis[1][1] = true;
	dfs(1, 1, "", 0);
}
           
bfs搜尋(+回溯法)例題剖析(一)

可以看到他輸出了一個解,但并不是最近的(186)。後來想了想,這樣有可能找不到解,比如走錯路了,一個死胡同,沒有回複vis[][] 為false, 結果沒路可走了。

不過隻想找到一個解的話應該如下測:

#include <iostream>
#include <string>

using namespace std;

int maze[35][55];
int dir[][2] = {{1, 0}, {0, -1}, {0, 1}, {-1, 0}};
char d[4] = {'D', 'L', 'R', 'U'};
bool vis[35][55];
int maxX = 4, maxY = 6;
bool done = false; 

// 判斷位址是否合法 
bool checkOk(int x, int y) {
	if (x <= maxX && x >= 1 && y <= maxY && y >= 1) {
		return true;
	}
	return false;
}


void dfs(int x, int y, string s, int num) {
	if (done) {
		return;
	}
	
	if (x == maxX && y == maxY) {
		cout << "the step you walk: " << num << endl;
		cout << s << endl;
		done = true;
		return;
	} 
	
	for (int i = 0; i < 4; i++) {
		int nx = x + dir[i][0];
		int ny = y + dir[i][1];
		if (!vis[nx][ny] && maze[nx][ny] == 0 && checkOk(nx, ny)) {
//			cout << nx << " " << ny << endl;
			vis[nx][ny] = true;
			dfs(nx, ny, s + d[i], num + 1);
			 vis[nx][ny] = false; // 回溯 
		}
	}
}

int main() {
	char temp;
	for (int i = 1; i <= maxX; i++){
		for (int j = 1; j <= maxY; j++){
			cin >> temp;
			maze[i][j] = temp -'0';
		}
	}
	vis[1][1] = true;
	dfs(1, 1, "", 0);
}
           
bfs搜尋(+回溯法)例題剖析(一)

不過對比bfs出來的結果,顯然不是最短的。

擴散

題目來源: 2020藍橋杯決賽c++ B組

bfs搜尋(+回溯法)例題剖析(一)

詳細見 2020藍橋國賽 c++ B(部分)

#include <iostream>
#include <cstring>
#include <queue>

using namespace std;

struct node{
	int x, y;
}; 

int maze[10000][10000];
int dir[][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};

bool check(int x, int y) {
	return x >= 0 && x <= 10000 && y >= 0 && y <= 10000;
}

void bfs() {
	// 此題的地圖渲染有點不同, 可以用地圖上的點記錄第幾分鐘 
	memset(maze, -1, sizeof(maze));
	queue<node> q;
	
	// 集體+3000  (0, 0)->(3000, 3000) 
	q.push({3000, 3000});
	maze[3000][3000] = 0;
	q.push({5020, 3011});
	maze[5020][3011] = 0;
	q.push({3011, 3014});
	maze[3011][3014] = 0;
	q.push({5000, 5000});
	maze[5000][5000] = 0;
	
	while(q.size()) {
		node cur = q.front();
		q.pop();
		// 這個停止條件留意一下
		if (maze[cur.x][cur.y] == 2020)
			return;
		for (int i = 0; i < 4; i++) {
			int nx = cur.x + dir[i][0];
			int ny = cur.y + dir[i][1];
			if (check(nx, ny) && maze[nx][ny] == -1) {
				q.push({nx, ny});
				// 以往一般是vis數組的操作
				maze[nx][ny] = maze[cur.x][cur.y] + 1;
			} 
		}
	}
}

int main() {
	bfs();
	
	int ans = 0;
	for(int i = 0; i < 10000; i++)
		for (int j = 0; j < 10000; j++)
			if (maze[i][j] >= 0)
				ans++;
	cout << ans << endl;  // 20312088
}
           

繼續閱讀