【洛谷】P1747 好奇怪的游戏(bfs)

穿越隧道

在这里插入图片描述

水题,与马的遍历相同

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#define x first
#define y second
using namespace std;
const int N = 210;
typedef pair<int,int> pii;
pii q[N *N];
int g[N][N];
int dx[] = {-2,-1,1,2,2,1,-1,-2,-2,2,2,-2};
int dy[] = {1,2,2,1,-1,-2,-2,-1,2,2,-2,-2};
int n,m;
bool st[N][N];
int dis[N][N];
int xa,ya,xb,yb;
void bfs(int sx, int sy){
	memset(st,0,sizeof(st));
	memset(dis,-1,sizeof(dis));
	dis[sx][sy] = 0;
	int hh = 0, tt = 0;
	q[0] = {sx,sy};
	st[sx][sy] = true;
	while(hh <= tt){
		pii t = q[hh++];
		for(int i = 0; i < 12; i++){
			int a = t.x + dx[i], b = t.y + dy[i];
			if(a >= 1 && a <= 20 && b >= 1 && b <= 20 && !st[a][b] && dis[a][b] == -1){
				dis[a][b] = dis[t.x][t.y] + 1;
				q[++tt] = {a,b};
			}
		}
	}
}
int main(){
	cin >> xa >> ya >> xb >> yb;
	bfs(xa,ya);
	cout << dis[1][1] << endl;
	bfs(xb,yb);
	cout << dis[1][1];
} 
 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值