思路
DFS深度优先搜索
解题过程
从矩阵的四周边界中的陆地进行深度优先搜索,将访问过的陆地进行标记,所有边界位置都进行尝试后,还没被访问过的陆地数即为飞地的数量
Code
class Solution {int dir[][] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };static int vis[][];int row;int col;public int numEnclaves(int[][] grid) {int ans = 0;row = grid.length;col = grid[0].length;vis = new int[row][col];for (int i = 0; i < row; i++) {if (grid[i][0] == 1 && vis[i][0] == 0)dfs(i, 0, grid);if (grid[i][col - 1] == 1 && vis[i][col - 1] == 0)dfs(i, col - 1, grid);}for (int i = 0; i < col; i++) {if (grid[0][i] == 1 && vis[0][i] == 0)dfs(0, i, grid);if (grid[row - 1][i] == 1 && vis[row - 1][i] == 0)dfs(row - 1, i, grid);}for (int i = 0; i < row; i++) {for (int j = 0; j < col; j++) {if (grid[i][j] == 1 && vis[i][j] == 0)ans++;}}return ans;}public void dfs(int x, int y, int[][] grid) {vis[x][y] = 1;for (int i = 0; i < 4; i++) {int newx = x + dir[i][0];int newy = y + dir[i][1];if (0 <= newx && newx < row && 0 <= newy && newy < col && vis[newx][newy] == 0 && grid[newx][newy] == 1) {dfs(newx, newy, grid);}}}
}作者:菜卷
链接:https://leetcode.cn/problems/number-of-enclaves/solutions/3032932/fei-di-de-shu-liang-by-ashi-jian-chong-d-nuvr/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。