1020.飞地的数量
1020.飞地的数量
题解
BFS或者DFS,这题的思路就是把边框当作搜索的点,那么能搜索到的就是能走通的,即代码中的vis,进行遍历即可算出搜索不到的,就是答案了
代码
package main func numEnclaves(grid [][]int) int { var dirs = []struct{ x, y int }{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} var vis = make([][]bool, len(grid)) for i, v := range grid { vis[i] = make([]bool, len(v)) } var dfs func(int, int) dfs = func(x, y int) { if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) || vis[x][y] || grid[x][y] == 0 { return } vis[x][y] = true for _, v := range dirs { dfs(x+v.x, y+v.y) } } for i := range grid { dfs(i, 0) dfs(i, len(grid[0])-1) } for i := 0; i <= len(grid[0])-1; i++ { dfs(0, i) dfs(len(grid)-1, i) } ans := 0 for i, v := range grid { for j := range v { if grid[i][j] == 1 && vis[i][j] == false { ans++ } } } return ans }