diff --git a/01Matrix.java b/01Matrix.java new file mode 100644 index 00000000..458b35a3 --- /dev/null +++ b/01Matrix.java @@ -0,0 +1,46 @@ +// TimeComplexity: O(m*n) +// SpaceComplexity: O(m*n) +// Explanation: I start by marking all 1s as -1 to indicate unvisited cells and enqueue all 0-cells. +// Then, I perform BFS layer by layer, updating each neighbor cell with its distance from the nearest 0. +// I increase the distance after each BFS layer to ensure all cells get the minimum distance from a 0. +// This guarantees every cell is updated once and efficiently. +class Solution { + public int[][] updateMatrix(int[][] mat) { + int m = mat.length; + int n = mat[0].length; + Queue q = new LinkedList<>(); + int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}}; + for(int i =0; i=0 && nr=0 && nc=0 && r=0 && c q = new LinkedList<>(); +// q.add(sr); +// q.add(sc); +// while(!q.isEmpty()) { +// int currR = q.poll(); +// int currC = q.poll(); +// for(int i =0; i=0 && r=0 && c