1911 · 地图分析
LintCode原题链接:1911 · 地图分析
题目分析
将所有的陆地压入队列中,在宽搜即可。主要要将所有的路径初始化为-1。
源码
public class Solution {
/**
* @param grid: An array.
* @return: An integer.
*/
static final int N = 105;
static int[][] dist = new int[N][N];
static int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};
static int n, m;
public int maxDistance(int[][] grid) {
// Write your code here.
int m = grid.length;
int n = grid[0].length;
Queue<Point> q = new LinkedList<>();
for (int i = 0; i < n; i++) {
Arrays.fill(dist[i], -1);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 1) {
dist[i][j] = 0;//陆地的距离为0
q.add(new Point(i, j));
}
}
}
while (!q.isEmpty()) {
Point tmp = q.poll();
for (int i = 0; i < 4; i++) {
int tx = tmp.x + dx[i];
int ty = tmp.y + dy[i];
if (tx < 0 || tx >= m || ty < 0 || ty >= n) continue;
if (dist[tx][ty] == -1) {
dist[tx][ty] = dist[tmp.x][tmp.y] + 1;
q.add(new Point(tx, ty));
}
}
}
int ans = -1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ans = Math.max(ans, dist[i][j]);
}
}
return ans == 0 ? -1 : ans;
}
public static class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
}
1892 · 扫雷
LintCode原题链接:1892 · 扫雷
题目分析
判断起点处是否有雷,如果有雷,直接返回,否则将起点压入队列中。将路径初始化为-1,在宽搜中不断更新各个点的路径长,如果该点不是雷,就压入到队列中。最后路径不为-1的点即为所求。
源码
public class Solution {
/**
* @param Mine_map: an matrix represents the map.
* @param Start: the start position.
* @return: return an array including all reachable positions.
*/
public List<List<Integer>> Mine_sweeping(int[][] Mine_map, int[] Start) {
// write your code here
if (Mine_map == null || Mine_map.length == 0 || Start == null || Start.length == 0) return null;
int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};
int n = Mine_map.length;
int m = Mine_map[0].length;
int[][] dist = new int[n][m];
Queue<Point> q = new LinkedList<>();
List<List<Integer>> lists = new ArrayList<>();
int x = Start[0], y = Start[1];
if (Mine_map[x][y] == 0) {
List<Integer> list = new ArrayList<>();
list.add(x);
list.add(y);
lists.add(list);
} else {
for (int i = 0; i < n; i++) {
Arrays.fill(dist[i], -1);
}
dist[x][y] = 0;
q.add(new Point(x, y));
while (!q.isEmpty()) {
Point tmp = q.poll();
for (int i = 0; i < 4; i++) {
int tx = tmp.x + dx[i];
int ty = tmp.y + dy[i];
if (tx < 0 || tx >= n || ty < 0 || ty >= m) continue;
if (dist[tx][ty] == -1) {
dist[tx][ty] = dist[tmp.x][tmp.y] + 1;
if (Mine_map[tx][ty] == 1) q.add(new Point(tx, ty));
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (dist[i][j] != -1) {
List<Integer> list = new ArrayList<>();
list.add(i);
list.add(j);
lists.add(list);
}
}
}
}
return lists;
}
}