当前位置:网站首页>Golang force buckle leetcode 1020 Number of enclaves

Golang force buckle leetcode 1020 Number of enclaves

2022-07-06 08:22:00 cheems~

1020. The number of enclaves

1020. The number of enclaves

Answer key

BFS perhaps DFS, The idea of this question is to take the border as the search point , Then what can be searched is what can be accessed , In the code vis, You can calculate what you can't find by traversing , That's the answer

Code

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
}

原网站

版权声明
本文为[cheems~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131832162052.html