Graph DFS Samrat

mail@pastecode.io avatar
unknown
java
19 days ago
2.0 kB
24
Indexable
Never
// leetcode 695 ==================

class Solution {
    public int findArea(int[][] grid, int i, int j, int n, int m){
        if(i<0 || j<0 || i>=n || j>=m || grid[i][j] == 0){
            return 0;
        }

        grid[i][j] = 0;

        int lArea = findArea(grid,i,j-1,n,m);
        int uArea = findArea(grid,i-1,j,n,m);
        int rArea = findArea(grid,i,j+1,n,m);
        int dArea = findArea(grid,i+1,j,n,m);   

        int myArea =  lArea + rArea + uArea + dArea + 1;
        
        return myArea;
    }
    public int maxAreaOfIsland(int[][] grid) {
        int maxArea = 0;

        int n = grid.length;
        int m = grid[0].length;

        for(int i=0; i<n; i++){
            for(int j=0; j<m; j++){
                if(grid[i][j] == 1){
                    int currArea = findArea(grid,i,j,n,m);

                    maxArea = Math.max(maxArea, currArea);
                }
            }
        }

        return maxArea;
    }
}






// leetcode 130 ======================


class Solution {
    public void changeToHash(int i, int j, int n, int m, char[][] board){
        if(i<0 || j<0 || i>=n || j>=m || board[i][j] != 'O'){
            return;
        }

        board[i][j] = '#';

        changeToHash(i,j-1,n,m,board);
        changeToHash(i-1,j,n,m,board);
        changeToHash(i,j+1,n,m,board);
        changeToHash(i+1,j,n,m,board);
    }
    public void solve(char[][] board) {
        int n = board.length;
        int m = board[0].length;

        for(int i=0; i<n; i++){
            for(int j=0; j<m; j++){
                if(i==0 || i==n-1 || j==0 || j==m-1){
                    if(board[i][j] == 'O'){
                        changeToHash(i,j,n,m,board);
                    }
                }
            }
        }

        for(int i=0; i<n; i++){
            for(int j=0; j<m; j++){
                if(board[i][j] == '#'){
                    board[i][j] = 'O';
                } else if(board[i][j] == 'O'){
                    board[i][j] = 'X';
                }
            }
        }
    }
}
Leave a Comment