zoukankan      html  css  js  c++  java
  • BFS八数码

    BFS八数码问题:

    #include <iostream>
    #include <cstring>
    #include <queue>
    #include <unordered_map>
    using namespace std;
    
    int bfs(string start)
    {
        string end = "12345678x";
        queue<string> q;
        unordered_map<string, int>d;
        q.push(start);
        d[start] = 0;
        int dx[4] = {-1,1,0,0},dy[4] = {0,0,1,-1};
        while(!q.empty())
        {
            string s = q.front();
            q.pop();
            int distance = d[s];
            if(s == end) return distance;
            int k = s.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)
                {
                    swap(s[k],s[a*3+b]);
                    if(!d.count(s))
                    {
                        d[s] = distance + 1;
                        q.push(s);
                    }
                    swap(s[k],s[a*3+b]);
                }
            }
            
        }
        
        return -1;
    }
    int main()
    {
        string start;
        cin>>start;
        cout<<bfs(start)<<endl;
    }

     注意:d.count(s)表示unordered_map类型的d键对应值的数量

  • 相关阅读:
    1033.采药1
    G——胜利大逃亡 (BFS)
    POJ 3278 Catch That Cow
    C
    11.17 dfs poj1979 Red and Black
    11.11反思
    kmp笔记
    dfs bfs
    1113
    python 类方法
  • 原文地址:https://www.cnblogs.com/longxue1991/p/12668986.html
Copyright © 2011-2022 走看看