LeetCode: Number of Enclaves Posted on July 22, 2019July 26, 2020 by braindenny Number of Enclaves Similar Problems: CheatSheet: Leetcode For Code Interview CheatSheet: Common Code Problems & Follow-ups Tag: #island Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land) A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid. Return the number of land squares in the grid for which we cannot walk off the boundary of the grid in any number of moves. Example 1: Input: [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]] Output: 3 Explanation: There are three 1s that are enclosed by 0s, and one 1 that isn't enclosed because its on the boundary. Example 2: Input: [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]] Output: 0 Explanation: All 1s are either on the boundary or can reach the boundary. Note: 1 <= A.length <= 500 1 <= A[i].length <= 500 0 <= A[i][j] <= 1 All rows have the same size. Github: code.dennyzhang.com Credits To: leetcode.com Leave me comments, if you have better ways to solve. Solution: // https://code.dennyzhang.com/number-of-enclaves // Basic Ideas: dfs // Complexity: Time O(n), Space O(1) func dfs(A [][]int, i int, j int, count *int) bool { rowCnt, colCnt := len(A), len(A[0]) if i<0 || i>=rowCnt || j<0 || j>=colCnt { return false } if A[i][j] != 1 { return true } *count++ A[i][j] = 2 res := true if !dfs(A, i+1, j, count) { res = false } if !dfs(A, i-1, j, count) { res = false } if !dfs(A, i, j-1, count) { res = false } if !dfs(A, i, j+1, count) { res = false } return res } func numEnclaves(A [][]int) int { res := 0 rowCnt, colCnt := len(A), len(A[0]) for i:=0; i<rowCnt; i++ { for j:=0; j<colCnt; j++ { if A[i][j] == 1 { count := 0 if dfs(A, i, j, &count) { res += count } } } } return res } Post Views: 0