题
思
面试题17.14
堆
leetcode1091
就是一道普普通通的bfs,额外记录一下当前步数即可
代码
面试题17.14
class Solution {
public int[] smallestK(int[] arr, int k) {
Queue<Integer> queue = new PriorityQueue<Integer>((a, b) -> b - a);
for (Integer i : arr) {
queue.offer(i);
if (queue.size() > k) {
queue.poll();
}
}
int[] res = new int[k];
int idx = 0;
while (!queue.isEmpty()) {
res[idx++] = queue.poll();
}
return res;
}
}
leetcode1091
class Solution {
Map<String, Integer> visited = new HashMap<String, Integer>();
Queue<String> queue = new LinkedList<String>();
public int shortestPathBinaryMatrix(int[][] grid) {
if (grid[0][0] == 1 || grid[grid.length - 1][grid.length - 1] == 1) {
return -1;
}
int minStep = -1;
visited.put("0,0", 1);
queue.offer("0,0");
while (!queue.isEmpty()) {
String[] posStr = queue.poll().split(",");
int row = Integer.valueOf(posStr[0]);
int col = Integer.valueOf(posStr[1]);
if (row == grid.length - 1 && col == grid.length - 1) {
minStep = visited.get(row + "," + col);
break;
}
bfs(row, col, grid);
}
return minStep;
}
private void bfs(int row, int col, int[][] grid) {
int step = visited.get(row + "," + col) + 1;
int[][] possiblePos = { { row - 1, col - 1 }, { row - 1, col }, { row - 1, col + 1 }, { row, col - 1 },
{ row, col + 1 }, { row + 1, col - 1 }, { row + 1, col }, { row + 1, col + 1 } };
for (int[] pos : possiblePos) {
if (pos[0] >= 0 && pos[0] < grid.length && pos[1] >= 0 && pos[1] < grid.length && grid[pos[0]][pos[1]] == 0
&& !visited.containsKey(pos[0] + "," + pos[1])) {
queue.offer(pos[0] + "," + pos[1]);
visited.put(pos[0] + "," + pos[1], step);
}
}
}
}