B14 BFS 八数码难题

视频链接:B14 BFS 八数码难题_哔哩哔哩_bilibili

 

Luogu P1379 八数码难题

#include <iostream>
#include <algorithm>
#include <queue>
#include <unordered_map>
using namespace std;

char c; string str;
unordered_map<string,int> d; 
queue<string> q;
int dx[4]={-1, 0, 1, 0};
int dy[4]={0, 1, 0, -1};

int bfs(string str){   
  q.push(str);
  string end="123804765"; //目标状态
  while(q.size()){
    auto s=q.front(); q.pop();
    if(s==end) return d[s]; //到达目标
    int k=s.find('0');
    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)continue;
      int dis=d[s]; //记住步数
      swap(s[k], s[a*3+b]); //交换
      if(!d.count(s))d[s]=dis+1,q.push(s);
      swap(s[k], s[a*3+b]); //还原
    }
  }
}
int main(){
  for(int i=0; i<9; i++)cin>>c, str+=c;
  cout << bfs(str);
  return 0;
}

 

#include<bits/stdc++.h>
using namespace std;

string str,ms="123804765";
queue<string> q;
map<string,int> d;
int dx[]={-1,0,1,0},dy[]={0,1,0,-1};

int bfs(string str){
  q.push(str);
  while(q.size()){
    auto s=q.front(); q.pop();
    if(s==ms) return d[s];
    int k=s.find('0'); //
    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>2||b<0||b>2)continue;
      string t=s;
      swap(t[k],t[a*3+b]); //
      if(!d.count(t)) d[t]=d[s]+1, q.push(t);
    }
  }
}
int main(){
  cin>>str;
  cout<<bfs(str);
}

 

posted @ 2022-05-28 13:22  董晓  阅读(1120)  评论(0)    收藏  举报