题目地址:
https://www.lintcode.com/problem/can-reach-the-endpoint/description
给定一个二维矩阵, 1 1 1代表空地, 0 0 0代表障碍物, 9 9 9代表终点。每一步只能走到相邻的格子上去,不能走到障碍物上。问从 ( 0 , 0 ) (0,0) (0,0)出发,是否可以走到数字为 9 9 9的那一格子上。
思路是BFS。可以用单向BFS或者双向BFS都可以。这里就使用单向BFS了。为了记录已访问过的点,我们新开一个class叫做Pair,并重写其equals和hashCode方法,以便于加入哈希表。代码如下:
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
public class Solution {
/**
* @param map: the map
* @return: can you reach the endpoint
*/
public boolean reachEndpoint(int[][] map) {
// Write your code here
// 判空
if (map == null || map.length == 0 || map[0].length == 0) {
return false;
}
// 如果出发点就是障碍物,直接返回false
if (map[0][0] == 0) {
return false;
}
// 如果出发点就是终点,那么显然可以到达,返回true
if (map[0][0] == 9) {
return true;
}
// 开个数组表示四个方向
int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
Queue<Pair> queue = new LinkedList<>();
queue.offer(new Pair(0, 0));
Set<Pair> visited = new HashSet<>(queue);
while (!queue.isEmpty()) {
Pair cur = queue.poll();
// 向四个方向走一步
for (int i = 0; i < 4; i++) {
int x = cur.x + dirs[i][0];
int y = cur.y + dirs[i][1];
Pair pair = new Pair(x, y);
// 如果未出界,且未被访问过,则说明该步可以走,进行下一步逻辑
if (inBound(map, x, y) && !visited.contains(pair)) {
// 如果这一步已经到达终点,则返回true;否则加入queue待访问
if (map[x][y] == 9) {
return true;
} else if (map[x][y] == 1) {
queue.offer(pair);
visited.add(pair);
}
}
}
}
return false;
}
private boolean inBound(int[][] map, int x, int y) {
return 0 <= x && x < map.length && 0 <= y && y < map[0].length;
}
class Pair {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
Pair p = (Pair) o;
return x == p.x && y == p.y;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
}
}
时空复杂度 O ( n ) O(n) O(n), n n n为矩阵的size。