LeetCode 1020. Number of Enclaves
原题链接在这里:https://leetcode.com/problems/number-of-enclaves/
题目:
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.
题解:
For the bondary cell, perform DFS starting from it. Convert all 1 connecting to boundary to 0.
Iterate A again and count how many cell are still 1.
Time Complexity: O(m*n). m = A.length. n = A[0].length.
Space: O(m*n). stack space.
AC Java:
1 class Solution { 2 public int numEnclaves(int[][] A) { 3 if(A == null || A.length == 0){ 4 return 0; 5 } 6 7 int m = A.length; 8 int n = A[0].length; 9 for(int i = 0; i<m; i++){ 10 dfs(A, i, 0); 11 dfs(A, i, n-1); 12 13 } 14 15 for(int j = 0; j<n; j++){ 16 dfs(A, 0, j); 17 dfs(A, m-1, j); 18 } 19 20 int res = 0; 21 for(int i = 0; i<m; i++){ 22 for(int j = 0; j<n; j++){ 23 if(A[i][j] == 1){ 24 res++; 25 } 26 } 27 } 28 29 return res; 30 } 31 32 private void dfs(int [][] A, int i, int j){ 33 if(i<0 || i>=A.length || j<0 || j>=A[0].length || A[i][j]!= 1){ 34 return; 35 } 36 37 A[i][j] = 0; 38 dfs(A, i+1, j); 39 dfs(A, i-1, j); 40 dfs(A, i, j+1); 41 dfs(A, i, j-1); 42 } 43 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步