Q8 Coloring A Border - LeetCode 1034

PHOTO EMBED

Sat Apr 22 2023 16:55:52 GMT+0000 (Coordinated Universal Time)

Saved by @Ayush_dabas07

class Solution {
    public int[][] colorBorder(int[][] grid, int row, int col, int color) {
        /*Q-1 of graph playlist , we will fire DFS to find component and 
        also pass a count(which will keep track of same color neighours) , we will make the
        element visited by making its value negative 

        while backtracking we will change elements to positive which have count == 4 as those 
        will not be colored as they are not on the boundary
         */

        //taking out current color for component and firing DFS
        int comp = grid[row][col];
        int m = grid.length , n = grid[0].length;
        
        DFS(grid , row , col , comp , m , n);

        //changing negative elements to color
        for(int i = 0 ;i < m;i++){
            for(int j = 0 ; j < n ; j++){
                if(grid[i][j] < 0)
                grid[i][j] = color;
            }
        }
        return grid;
    }

    //direction variable for making calls
    public int[][] dir = {{0,1},{1,0},{0,-1},{-1,0}};

    public void DFS(int[][] grid, int row, int col, int comp , int m , int n ){
        
        grid[row][col] = -comp; //marking visited 
        int count = 0 ; 
        for(int i =0 ; i < 4;i++){
            int rowdash = row + dir[i][0];
            int coldash = col + dir[i][1];
            
            //base condition if neighour is not valid
            if(rowdash < 0 || coldash < 0 || rowdash >= m || coldash >= n ||
            Math.abs(grid[rowdash][coldash]) != comp)
            continue;
            
            //if neighour is valid count++
            count ++; 

            //if neighour is not visited call it
            if(grid[rowdash][coldash] > 0 )
            DFS(grid , rowdash , coldash , comp , m , n);
        }
        //while backtracking checking if its a boundary element
        //if all neighours are equal to comp its not a boundary element
        if(count == 4)
        grid[row][col] = comp;
    }
}











content_copyCOPY

https://leetcode.com/problems/coloring-a-border/