每日一题 — 2020 - 05 - 11

bfs,但是有点巧妙?还是自己没理解好原本的题,没转换好

题目链接

解题思路:

  • 就是常规的bfs,只不过处理点的时候有点技巧
  • (应该也不算技巧)只是让原本要出发点的dist值为0,然后存入队列中,然后排着去搜索就OK
  • 还是挺简单的,可能想的有点慢
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;

typedef pair<int,int> PII;

const int N = 510;

int dist[N][N];

int idx[4] = {0,0,1,-1};
int idy[4] = {1,-1,0,0};
int n, m;

queue<PII> q;

void bfs(){
	while(!q.empty()){
		PII t = q.front();
		q.pop();
		int x = t.first, y = t.second;
		for (int i = 0; i < 4; i ++){
			int xx = x + idx[i];
			int yy = y + idy[i];
			if (xx >= 1 && xx <= n && yy <= m && yy >= 1 && dist[xx][yy] == -1){
				dist[xx][yy] = dist[x][y] + 1;
				q.push({xx,yy});
			}
		}
	}
}

int main(){
	int  a, b;
	memset(dist,-1,sizeof dist);
	scanf("%d%d%d%d",&n,&m,&a,&b);

	for (int i = 0; i < a; i++){
		int x, y;
		scanf("%d%d",&x,&y);
		dist[x][y] = 0;
		q.push({x,y});
	}
	bfs();
	for (int i  = 0; i < b; i++){
		int x, y;
		scanf("%d%d",&x,&y);
		printf("%d\n", dist[x][y]);
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章