BFS例题(八数码)C++(Acwing)

该代码展示了如何使用广度优先搜索(BFS)算法,将给定的字符串转换成特定的九宫格格式。通过定义队列和距离数组,逐步探索所有可能的状态转换路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码:

#include <iostream>
#include <algorithm>
#include <queue>
#include <unordered_map>

using namespace std;

int bfs(string start)
{
    //定义目标状态
    string end = "12345678x";
    //定义队列和dist数组
    queue<string> q;
    unordered_map<string, int> d;
    //初始化队列和dist数组
    q.push(start);
    d[start] = 0;
    //转移方式
    int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1};
    while(q.size())
    {
        auto t = q.front();
        q.pop();
        //记录当前状态的距离,如果是最终状态则返回距离
        int distance = d[t];
        if(t == end) return distance;
        //查询x在字符串中的下标,然后转换为在九宫格中的坐标
        int k = t.find('x');
        int x = k / 3, y = k % 3;
    
        for(int i = 0; i < 4; i++)
        {
            //坐标偏移
            int a = x + dx[i], b = y + dy[i];
            //当前坐标没有越界
            if(a >= 0 && a < 3 && b >= 0 && b < 3)
            {
                //交换x,九宫格对应字符串下标
                swap(t[k], t[a * 3 + b]);
                //如果当前状态是第一次遍历,记录距离,入队
                if(!d.count(t))
                {
                    d[t] = distance + 1;
                    q.push(t);
                }
                //还原状态,为下一种转换情况做准备
                swap(t[k], t[a * 3 + b]);
            }
        }
    }
    //无法转换到目标状态,返回-1
    return -1;
}
int main()
{
    string start;
    for(int i = 0; i < 9; i++)
    {
        char c;
        cin >> c;
        start += c;            
    }
    
    cout << bfs(start) << endl;
    
    return 0;
}

### C++ 实现八数码问题的广度优先搜索算法 为了实现八数码问题的解决方案,可以采用广度优先搜索(BFS),该方法是一种迭代的方法,在探索下一层之前会先遍历所有的相邻位置[^1]。 下面是一个基于C++语言的具体实现: ```cpp #include <iostream> #include <queue> #include <unordered_map> #include <vector> #include <array> using namespace std; struct Puzzle { array<int, 9> board; int pos_x; // Position of empty slot ('x') }; // Function to convert the current state into a unique key for hashing. string getKey(const array<int, 9>& board) { string key = ""; for (int i : board) key += to_string(i); return key; } bool isGoalState(const array<int, 9>& board) { static const array<int, 9> goal_state{1, 2, 3, 4, 5, 6, 7, 8, 0}; return board == goal_state; } void printSolution(const vector<char>& path) { cout << "Path found: "; for(char move : path){ switch(move){ case 'U': cout << "Up "; break; case 'D': cout << "Down "; break; case 'L': cout << "Left "; break; case 'R': cout << "Right "; break; } } cout << endl; } pair<vector<char>, bool> bfsSolvePuzzle(Puzzle initial_puzzle) { unordered_map<string, pair<Puzzle, char>> parentMap; queue<pair<Puzzle, vector<char>>> q; q.push({initial_puzzle, {}}); while (!q.empty()) { auto [current, path] = q.front(); q.pop(); if (isGoalState(current.board)) { reverse(path.begin(), path.end()); return {path, true}; } string currentStateKey = getKey(current.board); int x = current.pos_x / 3; int y = current.pos_x % 3; vector<pair<int,int>> directions{{-1,0},{1,0},{0,-1},{0,1}}; for(size_t d=0;d<directions.size();d++){ int newX=x+directions[d].first; int newY=y+directions[d].second; if(newX>=0 && newX<3 && newY>=0 && newY<3){ Puzzle newPuzzle=current_puzzle; swap(newPuzzle.board[newX * 3 + newY],newPuzzle.board[current.pos_x]); newPuzzle.pos_x=newX*3+newY; string newState=getKey(newPuzzle.board); if(parentMap.find(newState)==parentMap.end()){ parentMap[newState]={currentStateKey,'UDLR'[d]}; q.emplace(newPuzzle,path); q.back().second.push_back('UDLR'[d]); } } } } return {{}, false}; } ``` 此代码片段定义了一个`bfsSolvePuzzle`函数来尝试通过BFS找到从初始状态到目标状态的一条路径。如果找到了一条有效的路径,则返回表示移动序列的结果;如果没有找到任何可能到达目标状态的方式,则返回未解决问题的信息[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值