二进制矩阵中的最短路径
题目
给你一个 n x n 的二进制矩阵 grid 中,返回矩阵中最短 畅通路径 的长度。如果不存在这样的路径,返回 -1 。
二进制矩阵中的 畅通路径 是一条从 左上角 单元格(即,(0, 0))到 右下角 单元格(即,(n - 1, n - 1))的路径,该路径同时满足下述要求:
路径途经的所有单元格都的值都是 0 。
路径中所有相邻的单元格应当在 8 个方向之一 上连通(即,相邻两单元之间彼此不同且共享一条边或者一个角)。
畅通路径的长度 是该路径途经的单元格总数。
示例 1:
输入:grid = [[0,1],[1,0]]
输出:2
示例 2:
输入:grid = [[0,0,0],[1,1,0],[1,1,0]]
输出:4
示例 3:
输入:grid = [[1,0,0],[1,1,0],[1,1,0]]
输出:-1
提示:
n == grid.length
n == grid[i].length
1 <= n <= 100
grid[i][j] 为 0 或 1
代码
class Solution {
public int shortestPathBinaryMatrix(int[][] grid)
{
if(grid==null) return -1;
int row = grid.length;
int col = grid[0].length;
boolean[][] visited = new boolean[row][col];
int count=0;
int[][] dir={{0,-1},{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1}};
Queue<int[]> queue = new LinkedList<>();
if(grid[0][0] == 0)
{
queue.offer(new int[]{0,0});
visited[0][0] = true;
}
while(!queue.isEmpty())
{
int size = queue.size();
for(int i=0;i<size;i++)
{
int[] point = queue.poll();
if(point[0]==row-1 && point[1]==col-1)
{
visited[point[0]][point[1]]=true;
return count+1;
}
for(int j=0;j<8;j++)
{
int x = point[0] + dir[j][0];
int y = point[1] + dir[j][1];
if(x < 0 || x >= row || y < 0 || y >= col
|| visited[x][y] || grid[x][y] == 1)
{
continue;
}
else
{
queue.offer(new int[]{x,y});
visited[x][y] = true;
}
}
}
count++;
}
return -1;
}
}
执行代码
滑动窗口最大值
题目
给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
返回 滑动窗口中的最大值 。
示例 1:
输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
输出:[3,3,5,5,6,7]
解释:滑动窗口的位置 最大值
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
示例 2:
输入:nums = [1], k = 1
输出:[1]
提示:
1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
1 <= k <= nums.length
代码
class Solution {
class MonotonicQueue {
LinkedList<Integer> q = new LinkedList<>();
public void push(int n) {
// 将比自己小的全部移除
while (!q.isEmpty() && q.getLast() < n) {
q.pollLast();
}
// 将自己放入队列
q.addLast(n);
}
// 队列中第一个元素就是最大值
public int max() {
return q.getFirst();
}
// 删除元素
public void pop(int n) {
if (n == max()) {
q.pollFirst();
}
}
}
public int[] maxSlidingWindow(int[] nums, int k) {
List<Integer> res = new ArrayList<>();
MonotonicQueue win = new MonotonicQueue();
for (int i = 0; i < nums.length; i++) {
if (i < k-1) {
// 先填满窗口的前 k - 1
win.push(nums[i]);
} else {
// 窗口向前滑动,加入新数字
win.push(nums[i]);
// 记录当前窗口的最大值
res.add(win.max());
// 移除最先进入窗口的元素
win.pop(nums[i-k+1]);
}
}
int[] arr = new int[res.size()];
for (int i = 0; i < res.size(); i++) {
arr[i] = res.get(i);
}
return arr;
}
}
执行结果
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/shortest-path-in-binary-matrix