This commit is contained in:
kkunkka
2025-07-25 17:28:31 +08:00
parent a379231dbb
commit 073d099577

View File

@@ -0,0 +1,50 @@
package com.dota.gridGraph._1293;
import java.util.ArrayDeque;
class Solution {
public int shortestPath(int[][] grid, int k) {
if (grid.length == 1 && grid[0].length == 1) {
return 0;
}
var queue = new ArrayDeque<int[]>();
k = Math.min(k, grid.length + grid[0].length - 1);
queue.add(new int[]{0, 0, k});
int cnt = 0;
var book = new boolean[grid.length][grid[0].length][k + 1];
var next = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
while (!queue.isEmpty()) {
int size = queue.size();
cnt++;
for (int i = 0; i < size; i++) {
var t = queue.poll();
int x = t[0], y = t[1], z = t[2];
for (int[] xy : next) {
var nextx = x + xy[0];
var nexty = y + xy[1];
if (nextx < 0 || nexty < 0 || nextx >= grid.length || nexty >= grid[0].length) continue;
if (nextx == grid.length - 1 && nexty == grid[0].length - 1) {
return cnt;
}
if (z == 0 && grid[nextx][nexty] == 1) {
continue;
}
if (grid[nextx][nexty] == 0 && !book[nextx][nexty][z]) {
book[nextx][nexty][z] = true;
queue.offer(new int[]{nextx, nexty, z});
continue;
}
if (grid[nextx][nexty] == 1 && !book[nextx][nexty][z - 1]) {
book[nextx][nexty][z - 1] = true;
queue.offer(new int[]{nextx, nexty, z - 1});
}
}
}
}
return -1;
}
}