BFS BFS example - grasshoppers jump

Use breadth-first search of the subject - to give you an initial state, ask how many steps to reach a certain state requires a minimum?

At this time, a width-first search, using each state queue into the queue, while the need to maintain a corresponding number of steps corresponding to the state.

Ado, close put the question! !

Grasshoppers jump

There are 9 plates, arranged in a circle.

Grasshoppers 8 wherein the filled tray 8, there is a blank disc.

We call these grasshoppers clockwise numbered from 1 to 8

Each grasshopper can jump to an adjacent empty dish,

Can then point force, grasshoppers jump across a neighboring empty tray.

Please you do the math, if you want to make grasshoppers changed their formation arranged in counter-clockwise,

And to maintain the same position a blank disc (that is, transposition 1-8, 2-7 transposition, ...), at least after the jump How many times?

Detailed Topic: This problem can be understood as every empty plate with his left and right can any of the four sides of the plate in a switching position. You can use the string to represent each state of the dish.

     The initial state is "123456780", the final state is "876,543,210."

Note that at this time, need to determine whether the current set of state have joined to go through, if only joined nearly did not join the queue, otherwise skip this state. Without this step will lead to complexity is too high, the result can not be calculated. (Very important)

code show as below:

#include <iostream>
#include <queue>
#include <set>
using namespace std;

int number = 0;
typedef struct state{
  string sta;
  int step;
  state(string a,int b){
    sta = a;
    step = b;
  }
}state;

string myswap(string s,int a,int b){
  string ss(s);
  char tmp = ss[a];
  ss[a] = ss[b];
  ss[b] = tmp;
  return ss;
}
string mys("123456780");
int bfs(string& a){
  set<string> se;
  queue<state> q;
  state s(a,0);
  q.push(s);
  se.insert(s.sta);
  while(!q.empty()){
    state tmp = q.front();
    if(tmp.sta.compare("876543210") == 0){
      return tmp.step;   
    }
    int index = tmp.sta.find('0');
    string b = myswap(tmp.sta,index,(index+1)%9);
    if(se.find(b) == se.end()){
      q.push(state(b,tmp.step+1));
      se.insert(b);
    }
    string c = myswap(tmp.sta,index,(index+2)%9);
    if(se.find(c) == se.end()){
      q.push(state(c,tmp.step+1));
      se.insert(c);
    }
    string d = myswap(tmp.sta,index,(9+index-1)%9);
    if(se.find(d) == se.end()){
      q.push(state(d,tmp.step+1));
      se.insert(d);
    }

    string e = myswap(tmp.sta,index,(9+index-2)%9);
    if(se.find(e) == se.end()){
      q.push(state(e,tmp.step+1));
      se.insert(e);
    }
    q.pop();
  }
  return 0;
} 

int main() {
  int number = bfs(mys);
  cout << number << endl;
  return 0;
}

 

Guess you like

Origin www.cnblogs.com/Alice-Fourier/p/12375542.html