天天看点

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
}
           

继续阅读