洛谷 P1379 八数码难题

代码如下:

#include<bits/stdc++.h>
using namespace std;
struct node{
	string s;
	int pos;
}star,en;
map<string,int>mp[2];
queue<node>q[2];
int main(){
	cin>>star.s;
	en.s="123804765";
	for(int i=0;i<9;i++){
		if(star.s[i]=='0') star.pos=i;
	}
	en.pos=4;
	q[0].push(star);
	q[1].push(en);
	mp[0][star.s]=1;
	mp[1][en.s]=1;
	int op=0;
	while(1){
		node x=q[op].front();
		q[op].pop();
		if(mp[1-op][x.s]){
			cout<<mp[op][x.s]+mp[1-op][x.s]-2;
			return 0;
		}
		for(int i=0;i<4;i++){
			node y=x;
			if(i==0){//you
				if(y.pos==2||y.pos==5||y.pos==8) continue;
				swap(y.s[x.pos],y.s[x.pos+1]);
				y.pos++;
				if(mp[op][y.s]) continue;
				mp[op][y.s]=mp[op][x.s]+1;
				q[op].push(y);
			}
			else if(i==1){//zuo
				if(y.pos==0||y.pos==3||y.pos==6) continue;
				swap(y.s[x.pos],y.s[x.pos-1]);
				y.pos--;
				if(mp[op][y.s]) continue;
				mp[op][y.s]=mp[op][x.s]+1;
				q[op].push(y);
			}
			else if(i==2){//shang
				if(y.pos==0||y.pos==1||y.pos==2) continue;
				swap(y.s[x.pos],y.s[x.pos-3]);
				y.pos-=3;
				if(mp[op][y.s]) continue;
				mp[op][y.s]=mp[op][x.s]+1;
				q[op].push(y);
			}
			else{//xia
				if(y.pos==7||y.pos==8||y.pos==6) continue;
				swap(y.s[x.pos],y.s[x.pos+3]);
				y.pos+=3;
				if(mp[op][y.s]) continue;
				mp[op][y.s]=mp[op][x.s]+1;
				q[op].push(y);
			}
		}
		op=1-op;
	}
	return 0;
}

 

相关推荐

  1. P1179 [NOIP2010 普及组] 数字统计

    2024-03-28 23:32:02       33 阅读
  2. p1216数字三角形

    2024-03-28 23:32:02       59 阅读
  3. P8823

    2024-03-28 23:32:02       54 阅读
  4. P2863

    2024-03-28 23:32:02       39 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-28 23:32:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-28 23:32:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-28 23:32:02       82 阅读
  4. Python语言-面向对象

    2024-03-28 23:32:02       91 阅读

热门阅读

  1. 移除元素——leetcode[1]

    2024-03-28 23:32:02       37 阅读
  2. SQL优化

    2024-03-28 23:32:02       41 阅读
  3. c++部分题

    2024-03-28 23:32:02       46 阅读
  4. 苹果病虫检测

    2024-03-28 23:32:02       38 阅读
  5. 防抖和节流的概念及区别

    2024-03-28 23:32:02       37 阅读
  6. 2024年数字IC秋招-沐曦-GPU验证-笔试题

    2024-03-28 23:32:02       38 阅读
  7. 【 [蓝桥杯 2013 省 B] 翻硬币】

    2024-03-28 23:32:02       45 阅读
  8. 初入C++

    初入C++

    2024-03-28 23:32:02      42 阅读
  9. 二、数据库管理员密码管理

    2024-03-28 23:32:02       38 阅读
  10. 看书标记【数据科学:R语言实战 5】

    2024-03-28 23:32:02       45 阅读