From db37f45f7186a0a9a1048465650b7e5ede33b4be Mon Sep 17 00:00:00 2001 From: Khevna Khona Date: Sun, 25 Jan 2026 16:58:15 -0500 Subject: [PATCH] completed dfs - 1 --- 01Matrix.kt | 44 ++++++++++++++++++++++++++++++++++++++++++++ FloodFill.kt | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 01Matrix.kt create mode 100644 FloodFill.kt diff --git a/01Matrix.kt b/01Matrix.kt new file mode 100644 index 00000000..acec0a86 --- /dev/null +++ b/01Matrix.kt @@ -0,0 +1,44 @@ +// Given a 01 matrix, we need to find the distance of the nearest 0 for each cell. we use bfs to solve this problem, we start from all the 0 cells and explore their neighbors. +// If the neighbor is unvisited (value -1), we update its distance and add it to the queue. We continue this process until all cells are processed. +// Time complexity is O(m*n) where m is number of rows and n is number of columns +// Space complexity is O(m*n) +class Solution { + fun updateMatrix(mat: Array): Array { + val dirs = arrayOf( + intArrayOf(-1,0), + intArrayOf(1, 0), + intArrayOf(0,-1), + intArrayOf(0, 1) + ) + val m = mat.size + val n = mat[0].size + + val q = ArrayDeque() + + for(i in 0 until m) { + for (j in 0 until n) { + if (mat[i][j] == 0) { + q.addLast(intArrayOf(i,j)) + } else { + mat[i][j] *= -1 + } + } + } + + while(q.isNotEmpty()) { + val curr = q.removeFirst() + + for(dir in dirs) { + val r = curr[0] + dir[0] + val c = curr[1] + dir[1] + + if (r >= 0 && c>= 0 && r < m && c < n && mat[r][c] == -1) { + q.addLast(intArrayOf(r, c)) + mat[r][c] = mat[curr[0]][curr[1]] + 1 + } + } + } + + return mat + } +} \ No newline at end of file diff --git a/FloodFill.kt b/FloodFill.kt new file mode 100644 index 00000000..34e9f9a0 --- /dev/null +++ b/FloodFill.kt @@ -0,0 +1,41 @@ +// In this problen, we need to change the color of certain area in the image. we use bfs to solve this problem. +// We start from the given pixel and explore all its 4 directionally connected pixels that have the same color as the starting pixel. +// We change their color to the new color and continue this process until all connected pixels are processed. +// Time complexity is O(N) where N is the number of pixels in the image +// Space complexity is O(N) + +class Solution { + fun floodFill(image: Array, sr: Int, sc: Int, color: Int): Array { + val dirs = arrayOf( + intArrayOf(-1, 0), + intArrayOf(1, 0), + intArrayOf(0, -1), + intArrayOf(0, 1) + ) + + val m = image.size + val n = image[0].size + val oldColor = image[sr][sc] + if(oldColor == color) return image + val q : ArrayDeque = ArrayDeque() + + + + q.addLast(intArrayOf(sr,sc)) + image[sr][sc] = color + + while(q.isNotEmpty()) { + val curr = q.removeFirst() + for(dir in dirs) { + val r = curr[0] + dir[0] + val c = curr[1] + dir[1] + + if(r >= 0 && c>= 0 && r < m && c < n && image[r][c] == oldColor) { + image[r][c] = color + q.addLast(intArrayOf(r,c)) + } + } + } + return image + } +} \ No newline at end of file