Walls and Gates

Problem TC:O(n*m) SC:O(n*m) import java.util.* ; import java.io.*; class Pair { T a; T b; public Pair(T a, T b){ this.a =a; this.b = b; } public T getKey(){ return a; } public T getValue(){ return b; } } public class Solution { public static int[][] wallsAndGates(int[][] a, int n, int m) { // dfs from gate to empty room Queue q = new LinkedList(); for(int i=0;i

Jan 18, 2025 - 11:14
Walls and Gates

Problem

TC:O(n*m)
SC:O(n*m)

import java.util.* ;
import java.io.*; 
class Pair<T> {
    T a;
    T b;
    public Pair(T a, T b){
        this.a =a;
        this.b = b;
    }
    public T getKey(){
        return a;
    }
    public T getValue(){
        return b;
    }
}
public class Solution {
    public static int[][] wallsAndGates(int[][] a, int n, int m) {

        // dfs from gate to empty room
        Queue<Pair<Integer>> q = new LinkedList<>();

        for(int i=0;i<n;i++){
            for(int j = 0;j<m;j++){
                if(a[i][j]==0){
                    q.add(new Pair(i,j));
                }
            }
        }
        int dirs[][] = {{0,-1},{0,1},{-1,0},{1,0}};
        while(!q.isEmpty()){
            Pair<Integer> p  =   q.remove();
            int iq = p.getKey();
            int jq = p.getValue();
            for(int dir[]: dirs){
                int i = iq + dir[0];
                int j = jq + dir[1];
                if(i<n && j<m && i>=0 && j>=0 && a[i][j]== Integer.MAX_VALUE){
                    a[i][j] = a[iq][jq] +1;
                    q.add(new Pair(i,j));
                }
            }
        }
        return a;
    }

    // dfs from empty room to gate not recommended leading to TLE
       public static long update(int i, int j ,int[][] a, int n , int m,int [][] visited){
        //base case
        if(a[i][j] ==0) return 0;

        //i,j is the emty room
        long min  = Integer.MAX_VALUE;
        visited[i][j] = 1;
        int dirs[][] = {{0,-1},{0,1},{-1,0},{1,0}};
        for(int dir[] : dirs){
            int I = i+dir[0];
            int J = j+dir[1];
            if(I<n && J<m && I>=0 && J>=0 && a[I][J]!=-1 && visited[I][J]==0){
                min = Math.min(min, Math.abs(I-i) + Math.abs(J-j) + update(I,J,a,n,m,visited));
            }
        }
        visited[i][j] = 0;
        return min;
    }
}