4ms java dfs solution


  • 4
    L
    public class Solution {
    int[][] dirs = {{1,0},{-1,0},{0,-1},{0,1}};
    int maxLine;
    int maxCol;
    public int numIslands(char[][] grid) {
        int count = 0;
        if(grid == null) return count;
        maxLine = grid.length-1;
        if(maxLine < 0) return count;
        maxCol = grid[0].length-1;
        for(int i = 0; i<=maxLine;i++){
            for(int j = 0; j<=maxCol;j++){
                if(grid[i][j]=='1'){
                    dfs(grid, i, j);
                    count++;
                }
            }
        }
        return count;
    }
    private void dfs(char[][] grid, int line, int col){
        grid[line][col] = '0';
        for(int[] offset : dirs){
            int tmpline = line + offset[0];
            int tmpcol = col + offset[1];
            if(0<=tmpline && tmpline<=maxLine && 0<=tmpcol && tmpcol<=maxCol && grid[tmpline][tmpcol] == '1'){
                dfs(grid, tmpline, tmpcol);
            }
        }
    }
    

    }


Log in to reply
 

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