Code - DFS
Posted at 2022-05-05Updated at 2022-05-05 interview interview algorithm
leetcode
It seems that dp cannot solve this problem. Try DFS.
123456789101112131415161718192021222324252627282930313233343536373839404142434445
var empty intvar res intfunc uniquePathsIII(grid [][]int) int { // Take account of the ending cell empty = 1 res = 0 startX, startY := 0, 0 for i := 0; i < len(grid); i++ { for j := 0; j < len(grid[0]); j++ { if grid[i][j] == 1 { startX = i startY = j } else if grid[i][j] == 0 { empty++ } } } dfs(grid, startX, startY, 0) return res}func dfs(grid [][]int, x, y int, count int) { if x < 0 || y < 0 || x >= len(grid) || y >= len(grid[0]) || grid[x][y] == -1 { return } if grid[x][y] == 2 { if count == empty { res++ } return } // Used as visited grid[x][y] = -1 dfs(grid, x-1, y, count+1) dfs(grid, x, y-1, count+1) dfs(grid, x+1, y, count+1) dfs(grid, x, y+1, count+1) grid[x][y] = 0 }
Previous post: Code - Tree Next post: Code - Greedy