I met this question in the interview of Baidu


  • 0
    F

    the original solution:

        public int numIslands(char[][] grid) {
            int result = 0;
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[0].length; j++) {
                    if (grid[i][j] == '1') {
                        result++;
                        dfs(grid, i, j);
                    }
                }
            }
            return result;
        }
    
        private void dfs(char[][] grid, int i, int j) {
            if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] != '1') {
                return;
            }
            grid[i][j] = '2';
            dfs(grid, i, j + 1);
            dfs(grid, i + 1, j);
            dfs(grid, i, j - 1);
            dfs(grid, i - 1, j);
        }
    

    I met a variant of this question in the interview of Baidu, the problem is to find the maximum area of the island, which changes the original code a little bit:

        private static int num;
    
        public static int bigHomes(int[][] grid) {
            int result = 0;
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[0].length; j++) {
                    if (grid[i][j] == 1) {
                        num = 0;
                        dfs(grid, i, j);
                        result = Math.max(result, num);
                    }
                }
            }
            return result;
        }
    
        private static void dfs(int[][] grid, int i, int j) {
            if (i < 0 || i <= grid.length || j < 0 || j >= grid[0].length || grid[i][j] != 1) {
                return;
            }
            num++;
            grid[i][j] = 2;
            dfs(grid, i, j + 1);
            dfs(grid, i + 1, j);
            dfs(grid, i, j - 1);
            dfs(grid, i - 1, j);
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.