吹拉弹唱


  • Home
  • Archive
  • Categories
  • Tags
  • Books
  •  

© 2022 Kleon

Theme Typography by Makito

Proudly published with Hexo

Code - DFS

Posted at 2022-05-05Updated at 2022-05-05 interview  interview algorithm 

  • 980. Unique Paths III

# 980. Unique Paths III

leetcode

It seems that dp cannot solve this problem. Try DFS.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
var empty int
var res int

func 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

}

Share 

 Previous post: Code - Tree Next post: Code - Greedy 

© 2022 Kleon

Theme Typography by Makito

Proudly published with Hexo