广度搜索基础题目列表
广度优先特点
- 广度优先有一个特点,那就是到达的一定是最小的步数,
- 其实广度优先算法是把所有的状态写在了队列的每一个节点里面,所以需要结构体记录,然而深度优先是把状态记录在参数列表里面
- 对于广度优先的路径问题,因为可能是相同长度的路径,但是不同的上下左右入队顺序造就步数是相同的,但是路径不同
迷宫
https://www.jisuanke.com/problem/T1595
- 代码
#include <iostream>
#include <queue>
#include <string.h>
using namespace std;
int n, m;
int startx, starty;
char nums[11][11];
int dir[4][2] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
bool f;//表示的是一旦找到就可以直接返回了
bool gr[11][11];
bool in(int tx, int ty) {
return 0 <= tx && tx < n && 0 <= ty && ty < m;
}
void dfs(int x, int y) {
queue<pair<int, int>> q;
q.push({x, y});
gr[x][y] = true;
while(!q.empty()) {
//取得头部
pair<int, int> top = q.front();
q.pop();
int tx = top.first;
int ty = top.second;
for(int i = 0; i < 4; i++) {
int newx = tx + dir[i][0];
int newy = ty + dir[i][1];
if(in(newx, newy) && nums[newx][newy] != '*' && !gr[newx][newy]){
if(nums[newx][newy] == 'T') {
//cout << "jinri" << endl;
f = true;
return;
}
q.push({newx, newy});
gr[newx][newy] = true;
}
}
}
}
int main() {
cin >> n >> m;
//输入的地方要注意一下格式
for(int i = 0; i < n; i++) {
cin >> nums[i];
for(int j = 0; j < m; j++) {
if(nums[i][j] == 'S') {
startx = i, starty = j;
}
}
}
dfs(startx, starty);
if(f) {
cout << "yes";
}else {
cout << "no";
}
return 0;
}
蓝桥云客-迷宫(要求路径)
- 代码:
#include <iostream>
#include <string.h>
#include <queue>
using namespace std;
string nums[55];
bool gr[55][55];
int dir[4][2] = {{1, 0}, {0, -1}, {0, 1}, {-1, 0}};
char ur[4] = {'D', 'L', 'R', 'U'};
struct node{
int x, y;
string path;
node(int x, int y, string path):x(x), y(y), path(path) {}
};
bool in(int x, int y) {
return 0 <= x && x < 30 && 0 <= y && y < 50;
}
void bfs() {
node start(0, 0, "");
queue<node> q;
q.push(start);
gr[0][0] = true;
while(!q.empty()) {
node top = q.front();
q.pop();
if(top.x == 29 && top.y == 49) {
cout << top.path;
return;
}
for(int i = 0; i < 4; i++) {
int nowx = top.x + dir[i][0];
int nowy = top.y + dir[i][1];
if(in(nowx, nowy) && !gr[nowx][nowy] && nums[nowx][nowy] != '1') {
//cout << nowx << nowy << endl;
string nowpath = top.path + ur[i];
node nownode(nowx, nowy, nowpath);
q.push(nownode);
gr[nowx][nowy] = true;
}
}
}
}
int main()
{
// 请在此输入您的代码
for(int i = 0; i < 30; i++) {
cin >> nums[i];
//cout << nums[i] << endl;
}
//memset(gr, 0, sizeof(gr));
bfs();
return 0;
}
【推荐】2025 HarmonyOS 鸿蒙创新赛正式启动,百万大奖等你挑战
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】开源 Linux 服务器运维管理面板 1Panel V2 版本正式发布
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步