洛谷P1746 离开中山路(BFS、手打队列、板子题)

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

int n, x, y, ex, ey;
char s[1002][1002];

struct node {
	int x, y, step;
}q[1000001]; // x坐标, y坐标,到这个点时走了几步

int nex[4][2] = {0, -1, 1, 0, 0, 1, -1, 0};
bool book[1002][1002];

int main() {
	cin >> n;
	
	for(int i = 1; i <= n; i++) {
		for(int j = 1; j <= n; j++)
			cin >> s[i][j];
	}
	
	cin >> x >> y >> ex >> ey;

	int head = 1, tail = 1; // 指向队列头, 指向队列尾
	q[head].x = x;
	q[head].y = y;
	q[head].step = 0;
	// 起点先入队,步数为0
    tail++;
	// 尾 + 1,方便下一个点入队

	while(head < tail) {
		for(int i = 0; i < 4; i++) {
			int tx = q[head].x + nex[i][0];
			int ty = q[head].y + nex[i][1];
			
			if(tx < 1 || tx > n || ty < 1 || ty > n)	continue;
                // 越界			
			if(s[tx][ty] == '1' || book[tx][ty] == 1)	continue; 
			    // 障碍物, 已经走过

            // 符合条件的点,入队 ↓↓↓↓↓
			q[tail].x = tx;
			q[tail].y = ty;
			q[tail].step = q[head].step + 1;
			tail++;
    		book[tx][ty] = 1; // 标记已经走过了
		
			if(tx == ex && ty == ey) {
				cout << q[tail - 1].step; // 因为每个点入队后,tail都要 + 1变成新的,
                                          // 所以这里需要-1
				return 0;
			}
		}
		head++; // 头指针+1
	}
	return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值