跳到正文

个人记录

深度优先搜索进阶5-BFS进阶

bailuoboyu约 12 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 12 分钟

版本

  1. v1当前

课堂练习

P1379 八数码难题

代码与注释

C++
#include <bits/stdc++.h>
using namespace std;

string st, ed = "123804765"; // 初始状态和目标状态(固定为123804765)
long long dx[] = {-3, 3, -1, 1}; // 移动方向:上、下、左、右(基于一维数组索引)
map<string, bool> mp; // 用于记录已访问的状态,避免重复搜索

struct node {
    string s;    // 当前状态
    long long x;  // 空格位置(0的索引)
    long long step; // 到达当前状态的步数
};

void bfs() {
    queue<node> q;

    // 找到初始空格位置并入队
    for (long long i = 0; i < 9; i++) {
        if (st[i] == '0') {
            q.push({st, i, 0});
            mp[st] = true; // 标记初始状态为已访问
            break;
        }
    }

    while (!q.empty()) {
        node f = q.front();
        q.pop();

        // 如果当前状态等于目标状态,输出步数并返回
        if (f.s == ed) {
            cout << f.step;
            return;
        }

        // 尝试四个方向的移动
        for (long long i = 0; i < 4; i++) {
            long long xx = f.x + dx[i]; // 计算新位置

            // 边界检查:防止跨行移动(如从第1行最右移到第2行最左)
            if (((f.x == 2 || f.x == 5) && xx == f.x + 1) ||
                ((f.x == 3 || f.x == 6) && xx == f.x - 1)) {
                continue;
            }

            // 检查新位置是否合法
            if (xx >= 0 && xx < 9) {
                string ss = f.s; // 复制当前状态
                swap(ss[f.x], ss[xx]); // 移动空格

                // 如果新状态未被访问过
                if (!mp[ss]) {
                    mp[ss] = true; // 标记为已访问
                    q.push({ss, xx, f.step + 1}); // 新状态入队
                }
            }
        }
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    cin >> st; // 读取初始状态
    bfs();     // 执行广度优先搜索

    return 0;
}

P2730 [USACO3.2] 魔板 Magic Squares

代码与注释

C++
#include <bits/stdc++.h>
using namespace std;

string st = "12345678"; // 初始状态(第一行1234,第二行8765)
string ed;              // 目标状态(由输入确定)
map<string, bool> mp;   // 记录已访问的状态,避免重复搜索

struct node {
    string s;     // 当前魔板状态
    string path;  // 到达当前状态的操作序列
    long long step; // 操作步数
};

// 广度优先搜索函数
void bfs() {
    queue<node> q;
    q.push({st, "", 0}); // 初始状态入队
    mp[st] = true;        // 标记初始状态为已访问

    while (!q.empty()) {
        node f = q.front();
        q.pop();

        // 如果当前状态等于目标状态,输出结果
        if (f.s == ed) {
            cout << f.step << '\n' << f.path;
            return;
        }

        // 尝试三种操作:A、B、C(按字典序顺序)
        for (long long i = 0; i < 3; i++) {
            string ss = f.s; // 复制当前状态

            if (i == 0) { // 操作A:交换上下两行
                swap(ss[0], ss[7]);
                swap(ss[1], ss[6]);
                swap(ss[2], ss[5]);
                swap(ss[3], ss[4]);

                if (!mp[ss]) { // 如果新状态未被访问
                    mp[ss] = true;
                    q.push({ss, f.path + "A", f.step + 1});
                }
            }
            else if (i == 1) { // 操作B:将最右列插入最左
                swap(ss[3], ss[2]);
                swap(ss[2], ss[1]);
                swap(ss[1], ss[0]);
                swap(ss[4], ss[5]);
                swap(ss[5], ss[6]);
                swap(ss[6], ss[7]);

                if (!mp[ss]) {
                    mp[ss] = true;
                    q.push({ss, f.path + "B", f.step + 1});
                }
            }
            else { // 操作C:中央四格顺时针旋转
                swap(ss[2], ss[5]);
                swap(ss[2], ss[1]);
                swap(ss[1], ss[6]);

                if (!mp[ss]) {
                    mp[ss] = true;
                    q.push({ss, f.path + "C", f.step + 1});
                }
            }
        }
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    // 读取目标状态(8个数字)
    ed.resize(8);
    for (long long i = 0; i < 8; i++) {
        cin >> ed[i];
    }

    bfs(); // 执行广度优先搜索

    return 0;
}

家庭作业

P1588 [USACO07OPEN] Catch That Cow S

AC代码

C++
#include<bits/stdc++.h>
using namespace std;
long long st,ed,vis[1000000],t;
struct node{
	long long x,step;
};
void bfs(){
	queue<node>q;
	q.push({st,0});
	while(q.size()){
		node f=q.front();
		q.pop();
		if(f.x==ed){
			cout<<f.step<<'\n';
			return;
		}
		for(long long i=0;i<3;i++){
			if(i==0){
				long long xx=f.x-1;
				if(xx>=0&&!vis[xx]){
					q.push({xx,f.step+1});
					vis[xx]=1;
				}
			}
			else if(i==2){
				long long xx=f.x+1;
				if(!vis[xx]){
					q.push({xx,f.step+1});
					vis[xx]=1;
				}
			}
			else{
				long long xx=f.x*2;
				if(xx<=ed*2){
					q.push({xx,f.step+1});
					vis[xx]=1;
				}
			}
		}
	}
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
    cin>>t;
    while(t--){
       	cin>>st>>ed;
       	if(ed<st){
       		cout<<st-ed<<'\n';
       		continue;
		}
		for(long long i=0;i<=ed*2;i++){
			vis[i]=0;
		}
    	bfs();
    }
	return 0;
}

T582141星际跃迁追踪协议

AC代码

C++
#include<bits/stdc++.h>
using namespace std;
long long a,b,vis[1000000];
struct node{
	int z,b;
};
void bfs(){
	queue<node>q;
	vis[a]=1;
	q.push({a,0});
	while(q.size()){
		node f=q.front();
	    q.pop();
	    if(f.z==b){
	    	cout<<f.b;
	    	return;
		}
	    long long zz=f.z+1;
	    if(vis[zz]==0){
	    	q.push({zz,f.b+1});
	    	vis[zz]=1;
		}
		zz=f.z-1;
		if(vis[zz]==0){
	    	q.push({zz,f.b+1});
	    	vis[zz]=1;
		}
		zz=f.z*2;
		if(zz<=b*4&&vis[zz]==0){
	    	q.push({zz,f.b+1});
		}
	}
}
int main(){
	cin>>a>>b;
	bfs();
	return 0;
}

P1135 奇怪的电梯

AC代码

C++
#include<bits/stdc++.h>
using namespace std;
long long n,a,b,vis[1000000],mp[1000000];
struct node{
	int z,b;
};
void bfs(){
	queue<node>q;
	vis[a]=1;
	q.push({a,0});
	while(q.size()){
		node f=q.front();
	    q.pop();
	    if(f.z==b){
	    	cout<<f.b;
	    	return;
		}
	   	if(f.z+mp[f.z]<=n&&vis[f.z+mp[f.z]]==0){
	   		q.push({f.z+mp[f.z],f.b+1});
	   		vis[f.z+mp[f.z]]=1;
		}
	   	if(f.z-mp[f.z]>0&&vis[f.z-mp[f.z]]==0){
	   		q.push({f.z-mp[f.z],f.b+1});
	   		vis[f.z-mp[f.z]]=1;
		}
	}
	cout<<-1;
}
int main(){
	cin>>n>>a>>b;
	for(long long i=1;i<=n;i++){
		cin>>mp[i];
	}
	bfs();
	return 0;
}
原文