func movingCount(m int, n int, k int) int {
blocks := make([][]int, m)
visited := make([][]int, m)
for i := range blocks {
blocks[i] = make([]int, n)
visited[i] = make([]int, n)
for j := 0; j < n; j ++ {
blocks[i][j] = -1
visited[i][j] = -1
if getSum(i) + getSum(j) > k {
blocks[i][j] = 1
}
}
}
var dfs func(i, j int) int
dfs = func(i, j int) int {
res := 0
dirs := [][]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}
if blocks[i][j] != 0 {
res = 1
}
blocks[i][j] = 0
visited[i][j] = 1
for _, dir := range dirs {
x := i + dir[0]
y := j + dir[1]
if x >= 0 && x < m && y >= 0 && y < n && visited[x][y] != 1 && blocks[x][y] == -1 {
res += dfs(x, y)
}
}
visited[i][j] = -1
return res
}
return dfs(0, 0)
}
func getSum(num int) int {
sum := 0
for num != 0{
r := num % 10
sum += r
num /= 10
}
return sum
}
只是求机器人的运动范围,只用从右或者从下走就可以了,并且visited也不需要还原
func movingCount(m int, n int, k int) int {
blocks := make([][]int, m)
// visited := make([][]int, m)
for i := range blocks {
blocks[i] = make([]int, n)
// visited[i] = make([]int, n)
for j := 0; j < n; j ++ {
blocks[i][j] = -1
// visited[i][j] = -1
if getSum(i) + getSum(j) > k {
blocks[i][j] = 1
}
}
}
var dfs func(i, j int) int
dfs = func(i, j int) int {
res := 0
// dirs := [][]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}
dirs := [][]int{{0, 1}, {1, 0}}
if blocks[i][j] != 0 {
res = 1
}
blocks[i][j] = 0
//visited[i][j] = 1
for _, dir := range dirs {
x := i + dir[0]
y := j + dir[1]
// if x >= 0 && x < m && y >= 0 && y < n && visited[x][y] != 1 && blocks[x][y] == -1 {
if x >= 0 && x < m && y >= 0 && y < n && blocks[x][y] == -1 {
res += dfs(x, y)
}
}
//visited[i][j] = -1
return res
}
return dfs(0, 0)
}
func getSum(num int) int {
sum := 0
for num != 0{
r := num % 10
sum += r
num /= 10
}
return sum
}