BFS acht digitale

BFS acht digital:

#include <iostream> 
#include <cstring> 
#include <queue> 
#include <unordered_map>
 mit  Namespace std; 

int bfs ( String Start) 
{ 
    String end = " 12345678x " ; 
    Warteschlange < 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 };
    während (! q.empty ()) 
    { 
        String s = q.front (); 
        q.pop (); 
        int Abstand = d [s];
        wenn (s == end) return Abstand;
        int k = s.find ( ' x ' );
        int x = k / 3 , y = K% 3 ;
        für ( int i = 0 ; i <4 ; i ++ ) 
        { 
            int a = x + dx [i], b = y + dy [i];
            wenn (a> = 0 && a < 3 && b> = 0 && b < 3 ) 
            { 
                swap (s [k], s [a * 3 + b]);
                wenn (! d.count (n)) 
                { 
                    d [s] = Abstand + 1 ; 
                    q.push (s); 
                } 
                Swap (s [k], s [a * 3 + b]); 
            }
        } 
        
    } 
    
    Return - 1 ; 
} 
Int main () 
{ 
    String Start; 
    cin >> beginnen; 
    cout << bfs (Start) << endl; 
}

 

Ich denke du magst

Origin www.cnblogs.com/longxue1991/p/12668986.html
Empfohlen
Rangfolge