LeetCode: Flood Fill Solution
Recursive DFSApproach: DFS
Recursively traverse in 4 directions
Implementation
1var 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))45 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 }1516 const traverse = (r, c) => {17 if (!valid(r, c)) return1819 visited[r][c] = true2021 traverse(r - 1, c)22 traverse(r, c - 1)23 traverse(r + 1, c)24 traverse(r, c + 1)2526 image[r][c] = newColor27 }2829 traverse(sr, sc)3031 return image32}
References
Comments
Loading comments...
Tags
leetcode
array
matrix
dfs
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Merge Two Binary Trees
"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
Sliding window uses two pointers?