对于更大的输入网格,我得到TLE错误。我该如何解决呢? 我在这里使用回溯。
给定一个m * n网格,其中每个像元为0(空)或1(障碍)。只需一步,您就可以在一个空白单元格中上下移动,左移或右移。
如果最多可以消除k个障碍物,请返回从左上角(0,0)到右下角(m-1,n-1)的最小步数。如果找不到这样的步行,则返回-1。类解决方案{
int min= Integer.MAX_VALUE;
public int shortestPath(int[][] grid, int k) {
helper(grid,0,0,0,0,k);
return min==Integer.MAX_VALUE?-1:min;
}
void helper(int grid[][],int x, int y, int step, int obstacles,int k){
if(x<0 || y<0 || x>=grid.length || y>=grid[0].length || obstacles>k || grid[x][y]>1){
return;
}
if(x==grid.length-1 && y==grid[0].length-1){
min = Math.min(min,step);
return;
}
if(grid[x][y]==1) obstacles++;
int temp = grid[x][y];
grid[x][y]=2;
helper(grid,x+1,y,step+1,obstacles,k);
helper(grid,x,y+1,step+1,obstacles,k);
helper(grid,x-1,y,step+1,obstacles,k);
helper(grid,x,y-1,step+1,obstacles,k);
grid[x][y]=temp;
}
}
有任何人帮助吗?
答案 0 :(得分:1)
visited
个节点。这将通过队列和LinkedList通过
import java.util.Queue;
import java.util.LinkedList;
public class Solution {
static final int[][] directions = new int[][] {{0, 1}, {1, 0}, { -1, 0}, {0, -1}};
public static final int shortestPath(
final int[][] grid,
final int k
) {
final int rowLength = grid.length;
final int colLength = grid[0].length;
Queue<int[]> queue = new LinkedList<>();
boolean[][][] visited = new boolean[rowLength][colLength][k + 1];
visited[0][0][0] = true;
queue.offer(new int[] {0, 0, 0});
int minSteps = 0;
while (!queue.isEmpty()) {
final int size = queue.size();
for (int i = 0; i < size; i++) {
final int[] info = queue.poll();
final int row = info[0];
final int col = info[1];
final int currObstacble = info[2];
if (row == rowLength - 1 && col == colLength - 1) {
return minSteps;
}
for (int[] direction : directions) {
final int nextRow = direction[0] + row;
final int nextCol = direction[1] + col;
int nextObstacle = currObstacble;
if (nextRow > -1 && nextRow < rowLength && nextCol > -1 && nextCol < colLength) {
if (grid[nextRow][nextCol] == 1) {
nextObstacle++;
}
if (nextObstacle <= k && !visited[nextRow][nextCol][nextObstacle]) {
visited[nextRow][nextCol][nextObstacle] = true;
queue.offer(new int[] {nextRow, nextCol, nextObstacle});
}
}
}
}
minSteps++;
}
return -1;
}
}