田地行走-美团2023笔试(codefun2000)

28 篇文章 0 订阅
15 篇文章 0 订阅

题目链接
田地行走-美团2023笔试(codefun2000)

题目内容

塔子哥是一个农民,他有一片 n×m 大小的田地,共 n 行 m 列,其中行和列都用从 1 开始的整数编号,田地中有 k 个格子中埋有土豆。我们记第 a 行第 b 列的格子为 (a,b) 。塔子哥现在位于 (x1,y1) ,他想要移动到 (x2,y2) 处去收菜,但是他不想阻碍自己土地里土豆的生长情况,所以他不想在移动过程中碰到土豆。
塔子哥每次移动可以移动到与他所处格子的相邻的一格中,形式化地说,如果塔子哥位于 (x,y) ,则塔子哥可以移动到 (x−1,y) , (x+1,y) , (x,y−1) , (x,y+1) 的格子之一,但塔子哥不能移动到田地之外。
塔子哥想要在移动过程中,离这些土豆越远越好,而不是走最短路径。
这里定义两个格子之间的距离为曼哈顿距离,即格子 (a,b) 和 (c,d) 之间的距离是 ∣a−c∣+∣b−d∣ 。
塔子哥想知道,移动中与土豆之间距离的最小值最大可能是多少。
请注意,如果无论塔子哥如何移动,都会进入一个有土豆的格子的话,这个最大可能值为 0 。

输入描述

第一行三个整数,以空格分开,分别表示

输出描述

输出一行一个整数,表示移动过程中与土豆之间距离的最小值的可能最大值。

样例1

输入

5 6 2
2 1
2 3
1 1 5 1

输出

1

题解1

// 二分答案+搜索 
#include<bits/stdc++.h>
using namespace std;

const int N = 505;
const int dx[] = {0,1,0,-1}; // 方向数组 
const int dy[] = {1,0,-1,0};

int n, m, k, s1,t1,s2,t2;
int dis[N][N]; // dis[i][j]表示离放置土豆的位置的曼哈顿距离 
bool vis[N][N];

struct node1{
	int x, y, st;
}now1;
queue<node1> q1;

struct node2{
	int x, y;
}now2;

queue<node2> q2;

bool check(int x, int y){
	if(x < 1 || x > n || y < 1 || y > m || vis[x][y]) return false;
	return true;
}

void bfs1(){
	while(!q1.empty()){
		now1 = q1.front(); q1.pop();
		for(int i = 0; i < 4; i++){
			int tx = now1.x + dx[i];
			int ty = now1.y + dy[i];
			
			if(!check(tx, ty)) continue;
			dis[tx][ty] = now1.st + abs(tx - now1.x)+abs(ty - now1.y);
			vis[tx][ty] = 1;
			q1.push({tx, ty, dis[tx][ty]});
		}
	}
}
bool bfs2(int len){
	//printf("len = %d\n", len);
	if(dis[s1][t1] < len) return false;
	memset(vis, 0, sizeof vis);
	vis[s1][t1] = 1;
	while(!q2.empty()) q2.pop(); //这行代码必须有,清除上一个测试用例中的存在队列中的数据 
	q2.push({s1,t1});
	while(!q2.empty()){
		now2 = q2.front(); q2.pop();
		if(now2.x == s2 && now2.y == t2) return true;
		for(int i = 0; i < 4; i++){
			int tx = now2.x + dx[i];
			int ty = now2.y + dy[i];
			if(!check(tx, ty)) continue;
			if(dis[tx][ty] < len) continue;
			vis[tx][ty] = 1;
			q2.push({tx, ty});
		}
	}
	return false;
}
int main(){
	scanf("%d%d%d", &n, &m, &k);
	memset(vis, 0, sizeof vis);
	memset(dis, -1, sizeof dis);
	for(int i = 1, u, v; i <= k; i++){
		scanf("%d%d", &u, &v);
		vis[u][v] = 1; 
		dis[u][v] = 0;
		q1.push({u, v, 0});
	}
	bfs1(); // 标记每个位置离放置土豆的哈密顿距离 
	/*
	for(int i = 1; i <= n; i++){
		for(int j = 1; j <= m; j++){
			printf("%d ", dis[i][j]);
		}
		printf("\n");
	}*/
	scanf("%d%d%d%d", &s1,&t1,&s2,&t2);
	int L = -1, R = (n - 1) + (m - 1) + 1, mid;
	while(L + 1 < R){
		mid = (L + R)/2;
		if(bfs2(mid)) L = mid;
		else R = mid;
	}
	printf("%d\n", L);
	return 0;
}
  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值