用queue的添加元素时候,用offer不要用add
Queue 中 add() 和 offer()都是用来向队列添加一个元素。
在容量已满的情况下,add() 方法会抛出IllegalStateException异常,offer() 方法只会返回false
做算法题有异常,直接就凉了。
Modifier and Type | Method and Description |
---|---|
boolean |
add(E e) 将指定的元素插入到此队列中,如果可以立即执行此操作,而不会违反容量限制, true 在成功后返回 IllegalStateException 如果当前没有可用空间,则抛出IllegalStateException。 |
E |
element() 检索,但不删除,这个队列的头。 |
boolean |
offer(E e) 如果在不违反容量限制的情况下立即执行,则将指定的元素插入到此队列中。 |
E |
peek() 检索但不删除此队列的头,如果此队列为空,则返回 null 。 |
E |
poll() 检索并删除此队列的头,如果此队列为空,则返回 null 。 |
E |
remove() 检索并删除此队列的头。 |
分析一下这个题:
问的是离陆地区域最远的海洋区域,不能从海洋区域开始BFS,题目要求,转变一下说法就是从陆地可以到达海洋的最远距离,从陆地开始BFS,找到最后一块海洋。
还是人家说的填海造陆最形象生动了。
这个题用深搜就不好做了。
class Solution {
public int maxDistance(int[][] grid) {
int m = grid.length, n = grid[0].length;
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
queue.offer(new int[]{i, j});
}
}
}
//如果全是陆地或海洋
if (queue.isEmpty() || queue.size() == m * n) return -1;
int[][] next = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};
int level = -1;
while (!queue.isEmpty()) {
//将队列中当前所有元素取出,这是一层的陆地
int count = queue.size();
for (int i = 0; i < count; i++) {
int[] cur = queue.poll();
for (int[] nt: next) {
int nx = cur[0] - nt[0], ny = cur[1] - nt[1];
if (nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] == 0) {
grid[nx][ny] = 1;
queue.offer(new int[]{nx, ny});
}
}
}
level++;
}
return level;
}
}
/*
作者:dinary-2
链接:https://leetcode-cn.com/problems/as-far-from-land-as-possible/solution/java-bfs-by-dinary-2/
*/