My Java Solution


  • 0
    A

    Here's my code, please let me know if you think it can be improved~ Thank you !

    public int numIslands(char[][] grid) {
        int m = grid.length;
        if (m == 0) return 0;
        int n = grid[0].length;
        boolean[][] visit = new boolean[m][n];
        int count = 0;
        for (int i = 0 ; i < m ; ++i) {
            for (int j = 0 ; j < n ; ++j) {
                if (grid[i][j] == '0' || visit[i][j]) continue;
                helper(grid, i, j, visit);
                count++;
            }
        }
        return count;
    }
    
    public void helper(char[][] grid, int row, int column, boolean[][] visit) {
        if (row < 0 || row == grid.length || column < 0 || column == grid[0].length) return;
        if (visit[row][column] || grid[row][column] == '0') return;
        visit[row][column] = true;
        helper(grid, row - 1, column, visit);
        helper(grid, row + 1, column, visit);
        helper(grid, row, column - 1, visit);
        helper(grid, row, column + 1, visit);
    }

Log in to reply
 

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