BFS补题 迷宫 八数码

迷宫问题

链接: ACWing 844

#include <bits/stdc++.h>

using namespace std;

typedef pair<int,int> PII;

const int N = 200;
int g[N][N],f[N][N];
int m, n;
int dx[5] = {1,-1,0,0} , dy[5] = {0,0,-1,1};

void bfs(int a, int b){
	queue<PII> q;
	q.push({a,b});
	while (!q.empty()){
		PII start = q.front();
		q.pop();
		g[start.first][start.second] = 1;
		for (int i = 0; i < 4; i ++){
			int x = start.first + dx[i], y = start.second + dy[i];
			if (!g[x][y] && x>= 0 && x < n && y >= 0 && y < m){
				g[x][y] = 1;
				f[x][y] = f[start.first][start.second] + 1;
				q.push({x,y});
			} 
		}
	}
	cout << f[n-1][m-1];		
}

int main(){
	cin >> n >> m;
	for (int i = 0; i < n; i ++)
		for (int j = 0; j < m; j ++)
			cin >> g[i][j];
	bfs(0,0);
	return 0;
}

八数码

链接: ACWing 845

# include <bits/stdc++.h>

using namespace std;

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

int bfs(string start){
	q.push(start);
	string end = "12345678x";
	d[start] = 0;
	while(!q.empty()){
		string t = q.front();
		q.pop();
		//记录当前状态的距离,如果是最终状态则返回距离
		int distance = d[t];
		if (t == end) return distance;
		int k = t.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(t[k],t[3*a + b]);
				if (!d.count(t)){
					d[t] = distance + 1;
					q.push(t);
				}	
				/*一种状态有四种不同的转换情况(上、下、左、右),循环中需要遍历所有四种情况。
				这个地方是直接改变的原本状态,所以每一次循环结束要还原状态,“下一种情况“就是”上下左右“中的某一种*/
				swap(t[k],t[a*3+b]);			
			}
		} 		
	}
	return -1;
}

int main(){
	string op,start;
	for (int i = 0; i < 9; i ++){
		cin >> op;
		start += op;		
	}
	cout << bfs(start);
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值