# LeetCode: Flood Fill Solution

Recursive DFS

## Approach: DFS

Recursively traverse in 4 directions

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var floodFill = function (image, sr, sc, newColor) {2  const [m, n] = [image.length, image[0].length]3  const visited = Array.from({ length: m }, _ => Array(n).fill(false))4
5  const valid = (r, c) => {6    return (7      0 <= r &&8      r < m &&9      0 <= c &&10      c <= n &&11      !visited[r][c] &&12      image[r][c] === image[sr][sc]13    )14  }15
16  const traverse = (r, c) => {17    if (!valid(r, c)) return18
19    visited[r][c] = true20
21    traverse(r - 1, c)22    traverse(r, c - 1)23    traverse(r + 1, c)24    traverse(r, c + 1)25
26    image[r][c] = newColor27  }28
29  traverse(sr, sc)30
31  return image32}```

Original problem

leetcode

array

matrix

dfs

## Next Post

LeetCode: Merge Two Binary Trees

Sep 21, 2021

"You know you don't get bonus points for squishing all your code into the least number of lines" - someone

## Previous Post

LeetCode: Longest Substring Without Repeating Characters

Sep 18, 2021

Sliding window uses two pointers?

Search Posts