0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swift で Flood Fill(塗りつぶし)

Posted at

備忘用メモ

NOTE

コード

// sr: row  of graph
// sc: cell of graph
func floodFill(_ image: [[Int]], _ sr: Int, _ sc: Int, _ newColor: Int) -> [[Int]] {
    // ready
    let directions = [
        [ 0, -1], // top
        [ 1,  0], // right
        [ 0,  1], // bottom
        [-1,  0], // left
    ]
    let lenX = image.count
    let lenY = image[0].count
    var visited = [[Bool]](repeating: [Bool](repeating: false, count: lenY), count: lenX)
    let prevColor = image[sr][sc]

    // define dfs
    func dfs(_ graph: inout [[Int]], _ sr: Int, _ sc: Int) {
        if sr < 0 || sr > lenX-1 || sc < 0 || sc > lenY-1 { return } // invalid param
        if graph[sr][sc] != prevColor { return }
        if visited[sr][sc] { return }
        visited[sr][sc] = true
        graph[sr][sc] = newColor
        for dir in directions {
            let x = dir[0], y = dir[1]
            dfs(&graph, sr + x, sc + y)
        }
    }

    // run
    var _image = image
    dfs(&_image, sr, sc)
    return _image
}

ポイント

  • 隣接セルへの移動は directions 変数で管理

    • 移動先を変数として定義しておく。この問題では隣接セルが4セルのことを指していたが、たまに8セルのケースもあるのでその場合は directions 変数を変更すればよいだけになる
  • 無限ループ回避のために visited 変数で訪問済みかチェック(この問題の場合はなくても問題ないが基本的には必要)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?