diff --git a/01-matrix.java b/01-matrix.java new file mode 100644 index 00000000..4566d573 --- /dev/null +++ b/01-matrix.java @@ -0,0 +1,41 @@ +//TC: O(mXn) +//SC: O(m*n) for the queue + +class Solution { + int[][] dirs = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; + + public int[][] updateMatrix(int[][] mat) { + int m = mat.length; + int n = mat[0].length; + Queue q = new LinkedList<>(); + + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + if (mat[i][j] == 0) { + q.add(new int[] { i, j }); + } else { + mat[i][j] = -1; + } + } + } + int dist = 0; + while (!q.isEmpty()) { + int size = q.size(); + for (int i = 0; i < size; i++) { + int[] curr = q.poll(); + for (int[] dir : dirs) { + int nr = dir[0] + curr[0]; + int nc = dir[1] + curr[1]; + + //bounds check + if (nr >= 0 && nc >= 0 && nr < m && nc < n && mat[nr][nc] == -1) { + q.add(new int[]{nr,nc}); // this is to process the next level in bfs + mat[nr][nc] = dist + 1; + } + } + } + dist++; + } + return mat; + } +} \ No newline at end of file diff --git a/flodd-fill.java b/flodd-fill.java new file mode 100644 index 00000000..b0ef6e8e --- /dev/null +++ b/flodd-fill.java @@ -0,0 +1,29 @@ +//TC:O(m*n) +//SC:O(m*n) for the queue + +class Solution { + int[][] dirs = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; + + public int[][] floodFill(int[][] image, int sr, int sc, int color) { + int originalCol = image[sr][sc]; + if (originalCol == color) + return image; + dfs(image, sr, sc, color, originalCol); + return image; + } + + private void dfs(int[][] image, int sr, int sc, int color, int originalCol) { + //base + if (sr < 0 || sc < 0 || sr >= image.length || sc >= image[0].length || image[sr][sc] != originalCol) + return; + + //logic + image[sr][sc] = color; + for (int[] dir : dirs) { + int nr = sr + dir[0]; + int nc = sc + dir[1]; + dfs(image, nr, nc, color, originalCol); + } + + } +} \ No newline at end of file