八数码(bfs)

思路:

(1)用string来存储状态,用d来记录状态变换次数;

(2)在bfs过程中,先初始化(q,d);每次拿出队头状态,得到x的相对位置,再得到x的矩阵位置,向四个方向尝试走,如果可行,就先做变换,如果该状态没被使用过即没有走回头路,就更新放入队列,另一方面维护d距离;然后恢复现场保证其余三个方向继续使用;如果所有状态都探讨完毕也没有可行解,就输出-1;

代码:

#include

using namespace std;

int dx[] = {1,-1,0,0},dy[] = {0,0,1,-1};

void bfs(string start)
{
    queue q;
    unordered_map d;
    
    string end = "12345678x";
    
    q.push(start);
    d[start] = 0;
    while(!q.empty())
    {
        string tmp = q.front();
        int k = tmp.find('x');
        q.pop();
        
        int x = k/3,y = k%3;
        int dis = d[tmp];
        
        if(tmp == end)
        {
            cout << d[end] << endl;
            return;
        }
        
        for(int i = 0;i < 4;i ++)
        {
            int tx = x + dx[i],ty = y + dy[i];
            
            if(tx >=0 && ty >= 0 && tx < 3 && ty < 3)
            {
                swap(tmp[k],tmp[tx*3 + ty]);
                
                if(d.count(tmp) == 0)
                {
                    d[tmp] = dis + 1;
                    q.push(tmp);
                }
                
                swap(tmp[k],tmp[tx*3 + ty]);
            }
        }
    }
    
    cout << -1<> c;
        start = start + c;
    }
    
    bfs(start);
    
    return 0;
}

你可能感兴趣的:(宽度优先,算法,c++)