June 5th 2023

Flood fill — Swift

Problem Description permalink

An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.

You are also given three integers sr, sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].

To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color.

Return the modified image after performing the flood fill.

Solution permalink

typealias Color = Int
typealias Image = [[Int]]

struct Point {
let x: Int
let y: Int
}

extension Point: CustomStringConvertible {
var description: String {
return "(\(self.x), \(self.y))"
}
}

func inBounds(point: Point, for image: Image) -> Bool {
return point.x >= 0 && point.x < image.count && point.y >= 0 && point.y < image[0].count
}

func fourDirectionalPoints(from: Point, in image: Image) -> [Point] {
return [
Point(x: from.x + 1, y: from.y),
Point(x: from.x - 1, y: from.y),
Point(x: from.x, y: from.y + 1),
Point(x: from.x, y: from.y - 1)
]
.filter { point in
return inBounds(point: point, for: image)
}
}

func floodFillInt(image: Image, forTargetColor targetColor: Color, withColor fillColor: Color, atPoints points: [Point]) -> Image {
var nextPoints = points

guard let fillPoint = nextPoints.popLast() else {
return image
}


var nextImage = image

if (image[fillPoint.x][fillPoint.y] == targetColor){
nextImage[fillPoint.x][fillPoint.y] = fillColor

fourDirectionalPoints(from: fillPoint, in: image)
.forEach { p in
if image[p.x][p.y] != fillColor {
nextPoints.append(p)
}
}
}

return floodFillInt(image: nextImage, forTargetColor: targetColor, withColor: fillColor, atPoints: nextPoints)
}

class Solution {
func floodFill(_ image: [[Int]], _ sr: Int, _ sc: Int, _ color: Int) -> [[Int]] {
return floodFillInt(
image: image,
forTargetColor: image[sr][sc],
withColor: color,
atPoints: [
Point(x: sr, y: sc)
])
}
}

print(Solution().floodFill([[1,1,1],[1,1,0],[1,0,1]], 1, 1, 2))
print(Solution().floodFill([[0,0,0],[0,0,0]], 1, 0, 2))
print(Solution().floodFill([
[1,1,1],
[1,1,0],
[1,0,1]
]
, 1, 1, 2))

Discussion permalink

I don't like the typing that the original function used. I tried to be careful with typealiases and good function signatures to make this readable. I need to figure out testing in a swift playground because this is very testable and it would have been nice to have been supported by tests all of the way.