|
| 1 | +class Solution { |
| 2 | + func floodFill(_ image: [[Int]], _ sr: Int, _ sc: Int, _ newColor: Int) -> [[Int]] { |
| 3 | + var visited = Array(repeating:Array(repeating: false, count:image[0].count), count:image.count) |
| 4 | + var result = image |
| 5 | + if sr<0 || sr>image.count-1 || sc<0 || sc>image[0].count-1 { |
| 6 | + return image |
| 7 | + } |
| 8 | + let oldColor = image[sr][sc] |
| 9 | + if oldColor != newColor { |
| 10 | + fill(&result, sr, sc, oldColor, newColor, &visited) |
| 11 | + return result |
| 12 | + } else { |
| 13 | + return image |
| 14 | + } |
| 15 | + |
| 16 | + } |
| 17 | + |
| 18 | + func fill(_ result: inout [[Int]], _ sr: Int, _ sc: Int, _ color: Int, _ newColor: Int, _ visited: inout [[Bool]]) { |
| 19 | + guard sr>=0, sr<result.count, sc>=0, sc<result[0].count, visited[sr][sc]==false, result[sr][sc]==color else { |
| 20 | + return |
| 21 | + } |
| 22 | + visited[sr][sc] = true |
| 23 | + result[sr][sc] = newColor |
| 24 | + fill(&result, sr-1, sc, color, newColor, &visited) |
| 25 | + fill(&result, sr+1, sc, color, newColor, &visited) |
| 26 | + fill(&result, sr, sc-1, color, newColor, &visited) |
| 27 | + fill(&result, sr, sc+1, color, newColor, &visited) |
| 28 | + } |
| 29 | +} |
0 commit comments