6
public int shortestPath(int[][] grid, int k) {8
colLen = grid[0].length;9
MAXVAL = rowLen * colLen + 1;12
grid, k, 0, 0, 0, new boolean[rowLen][colLen], new Integer[rowLen][colLen][k + 1][4]);13
return path == MAXVAL ? -1 : path;23
// For each cell(row, col) explore all possible ways to reach it with minimum cost, hence we24
// consider the direction as well33
// Reached end of the matrix34
if (row == rowLen - 1 && col == colLen - 1 && k >= 0) return 0;36
// Couldn't find a valid path37
if (k < 0 || row < 0 || col < 0 || row >= rowLen || col >= colLen) return MAXVAL;39
if (dp[row][col][k][direction] != null) return dp[row][col][k][direction];41
// 4 options to choose a direction44
if (col + 1 < colLen && !visited[row][col + 1]) {45
visited[row][col + 1] = true;46
if (grid[row][col + 1] == 0) op1 = shortest(grid, k, row, col + 1, 3, visited, dp) + 1;47
else op1 = shortest(grid, k - 1, row, col + 1, 3, visited, dp) + 1;48
visited[row][col + 1] = false;53
if (col - 1 >= 0 && !visited[row][col - 1]) {54
visited[row][col - 1] = true;55
if (grid[row][col - 1] == 0) op2 = shortest(grid, k, row, col - 1, 2, visited, dp) + 1;56
else op2 = shortest(grid, k - 1, row, col - 1, 2, visited, dp) + 1;57
visited[row][col - 1] = false;62
if (row - 1 >= 0 && !visited[row - 1][col]) {63
visited[row - 1][col] = true;64
if (grid[row - 1][col] == 0) op3 = shortest(grid, k, row - 1, col, 0, visited, dp) + 1;65
else op3 = shortest(grid, k - 1, row - 1, col, 0, visited, dp) + 1;66
visited[row - 1][col] = false;71
if (row + 1 < rowLen && !visited[row + 1][col]) {72
visited[row + 1][col] = true;73
if (grid[row + 1][col] == 0) op4 = shortest(grid, k, row + 1, col, 1, visited, dp) + 1;74
else op4 = shortest(grid, k - 1, row + 1, col, 1, visited, dp) + 1;75
visited[row + 1][col] = false;78
dp[row][col][k][direction] = Math.min(Math.min(op1, op2), Math.min(op3, op4));79
return dp[row][col][k][direction];