NSUOJ3163深刻

一、题目描述

Description
有一个N * N的01矩阵。
'0’代表陆地,'1’代表墙,起点终点一定是陆地。
现在可以在陆地上建传送装置,装置只能建造一次,花费为两点间横坐标/纵坐标的差的平方和,(X1 - X2)2 + (Y1 - Y2)2。
问起点到终点的最小花费。

Input
第一行一个正整数N。
第二行输入起点S1 , T1 。
第二行输入终点S2 , T2 。
下面是N * N的01矩阵。
1 ≤ N ≤ 100
1 ≤ S1 , S2 ≤ N
1 ≤ T1 , T2 ≤ N
Output
输出最小花费。
Sample Input Copy
5
1 1
5 5
00001
11111
00111
00110
00110
Sample Output Copy
10

二、解题思路

这道题是一个大佬提供的思路,为什么要建造传送装置,因为被墙挡住了,过不去,如果能走到终点,自然也就不需要花费money去建造传送装置,自然为0,如果过不去,就得老老实实造了,我们需要两个数组,一个数组记录起点周围能建造装置的空地,用bfs进行扩散,一个数组记录终点周围能建造装置的空地,两个数组有了,直接暴力找出最小花费即可。

三、代码实现

#include <iostream>
#include <queue>
#include <cstring>
#include <cmath>
using namespace std;
int n, sx, sy, ex, ey;
int c1, c2, flag;
int ans = 999999999;
char mp[200][200];
int vis[200][200];
int dd[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };
struct node {
	int x, y;
}bg[100010], ed[100010];
void bfs(int x1, int y1, int x2, int y2, node a[], int& c, int f) {
	queue<node> q;
	vis[x1][y1] = 1;
	node cur;
	cur.x = x1;
	cur.y = y1;
	q.push(cur);
	a[++c] = cur;
	while (!q.empty()) {
		node now = q.front();
		q.pop();
		//证明能走通,就不需要建造,直接标记一下
		if (now.x == x2 && now.y == y2) {
			flag = 1;
			return;
		}
		for (int i = 0; i < 4; i++) {
			int x = now.x + dd[i][0];
			int y = now.y + dd[i][1];
			if (x<1 || x>n || y<1 || y>n || vis[x][y] || mp[x][y] == '1')
				continue;

			vis[x][y] = 1;
			node t; t.x = x; t.y = y;
			q.push(t);
			//将能够建造装置的坐标放入数组
			a[++c] = t;
		}
	}
}
int main()
{
	flag = c1 = c2 = 0;
	scanf("%d%d%d%d%d", &n, &sx, &sy, &ex, &ey);
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			cin >> mp[i][j];
		}
	}
	memset(vis, 0, sizeof(vis));
	bfs(sx, sy, ex, ey, bg, c1, flag);
	if (flag == 1) {
		//如果能够走通直接输出0,表示不需要建造
		printf("0\n");
	}
	else {
		memset(vis, 0, sizeof(vis));
		flag = 0;
		bfs(ex, ey, sx, sy, ed, c2, flag);
		//这句注释代码可以很直接的看出起点和终点有多少个能够建造的点
		//cout << c1 << " " << c2 << endl; 

		//暴力跑循环得出答案
		for (int i = 1; i <= c1; i++) {
			for (int j = 1; j <= c2; j++) {
				ans = min(ans, (bg[i].x - ed[j].x) * (bg[i].x - ed[j].x) +
					(bg[i].y - ed[j].y) * (bg[i].y - ed[j].y));
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值