算法:八数码(宽搜bfs)

八数码

用unordered_map来存储状态对应的字符串和步数。
从开始状态出发,检查当前的上下左右是否满足在3×3的格子中,如果满足并且当前的状态没有到达过,那么将此状态添加到队尾,并且将此状态添加到字典中。直到找到终止状态或者队列为空。

问题描述

在一个3×3的网格中,1~8这8个数字和一个“x”恰好不重不漏地分布在这3×3的网格中。

例如:

1 2 3
x 4 6
7 5 8
在游戏过程中,可以把“x”与其上、下、左、右四个方向之一的数字交换(如果存在)。

我们的目的是通过交换,使得网格变为如下排列(称为正确排列):

1 2 3
4 5 6
7 8 x
例如,示例中图形就可以通过让“x”先后与右、下、右三个方向的数字交换成功得到正确排列。

交换过程如下:

1 2 3 1 2 3 1 2 3 1 2 3
x 4 6 4 x 6 4 5 6 4 5 6
7 5 8 7 5 8 7 x 8 7 8 x
现在,给你一个初始网格,请你求出得到正确排列至少需要进行多少次交换。

输入格式

输入占一行,将3×3的初始网格描绘出来。

例如,如果初始网格如下所示:
1 2 3

x 4 6

7 5 8

则输入为:1 2 3 x 4 6 7 5 8

输出格式

输出占一行,包含一个整数,表示最少交换次数。

如果不存在解决方案,则输出”-1”。

输入样例:

2 3 4 1 5 x 7 6 8

输出样例

19

代码

#include
#include
#include
using namespace std;

int bfs(string start){
     
    string end = "12345678x";
    unordered_map<string, int> d;
    queue<string> q;
    
    q.push(start);
    d[start] = 0;
    int dir[4][2] = {
     -1, 0, 1, 0, 0, -1, 0, 1}; // 上下左右
    while(q.size()){
     
        string t = q.front();
        q.pop();
        if(t == end){
     
            return d[t];
        }
        int distance = d[t];
        int k = t.find('x');
        int a = k / 3, b = k % 3;
        for(int i = 0; i < 4; ++i){
     
            int x = a + dir[i][0], y = b + dir[i][1];
            if(x >= 0 && x < 3 && y >= 0 && y < 3){
     
                swap(t[k], t[x*3+y]);
                if(!d.count(t)){
     
                    q.push(t);                    
                    d[t] = distance + 1;    
                }
                swap(t[k], t[x*3+y]);
            }
        }
    }
    return -1;
}

int main(){
     
    string s;
    for(int i = 0; i < 9; ++i){
     
        string c;
        cin >> c;
        s += c;
    }
    cout << bfs(s) << endl;
    return 0;
}

原题链接

你可能感兴趣的:(算法,宽搜,bfs,八数码,unordered_map,queue)