首页 技术 正文
技术 2022年11月20日
0 收藏 718 点赞 2,307 浏览 1325 个字

2014-05-06 00:17

题目链接

原题:

Given a -D matrix represents the room, obstacle and guard like the following ( is room, B->obstacle, G-> Guard): B G G
B calculate the steps from a room to nearest Guard and set the matrix, like this B G G
B
Write the algorithm, with optimal solution.

题目:有一个二维矩阵表示的迷宫,其中G表示保安人员,B表示不可穿越的墙,其他位置均为空地。如果每次可以向东南西北四个方向移动一格,请计算出每个空格离最近的保安有多远。题目给出了一个示例。

解法:既然矩阵里可能有多个保安,我的思路是以各个保安为中心,进行广度优先搜索,搜索的过程中随时更新每个空格位置的最短距离,保证全部搜索完之后所有的结果都是最小的。单次BFS的时间代价是O(n^2)级别的。

代码:

 // http://www.careercup.com/question?id=4716965625069568
#include <queue>
#include <vector>
using namespace std; class Solution {
public:
void solve(vector<vector<int> > &matrix) {
// -1 for guard
// -2 for blockade
// 0 for room
// > 0 for distance n = (int)matrix.size();
if (n == ) {
return;
}
m = (int)matrix[].size();
if (m == ) {
return;
} int i, j; for (i = ; i < n; ++i) {
for (j = ; j < m; ++j) {
if (matrix[i][j] == -) {
doBFS(matrix, i, j);
}
}
}
};
private:
int n, m; bool inBound(int x, int y) {
return x >= && x <= n - && y >= && y <= m - ;
} void doBFS(vector<vector<int> > &matrix, int x, int y) {
queue<int> q;
static int dd[][] = {{-, }, {+, }, {, -}, {, +}};
int tmp;
int xx, yy;
int i;
int dist; q.push(x * m + y);
while (!q.empty()) {
tmp = q.front();
q.pop();
x = tmp / m;
y = tmp % m;
dist = matrix[x][y] > ? matrix[x][y] : ;
for (i = ; i < ; ++i) {
xx = x + dd[i][];
yy = y + dd[i][];
if (!inBound(xx, yy) || matrix[xx][yy] < ||
(matrix[xx][yy] > && matrix[xx][yy] <= dist + )) {
// out of boundary
// a guard or a blockade
// the distance is no shorter
continue;
}
matrix[xx][yy] = dist + ;
q.push(xx * m + yy);
}
}
}
};
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,074
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,551
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,399
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,176
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,811
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,892