想法
遞迴確認上下左右是否需要變顏色
程式碼
class Solution {
fun floodFill(image: Array, sr: Int, sc: Int, color: Int): Array {
val sourceColor = image[sr][sc]
if(sourceColor == color) return image
var resultImage = image
resultImage[sr][sc] = color
if (sr-1 >= 0 && image[sr-1][sc]==sourceColor){
resultImage = floodFill(resultImage, sr-1, sc, color)
}
if (sr+1 <= image.size-1 && image[sr+1][sc]==sourceColor) resultImage = floodFill(resultImage, sr+1, sc, color)
if (sc-1 >= 0 && image[sr][sc-1]==sourceColor) resultImage = floodFill(resultImage, sr, sc-1, color)
if (sc+1 <= image[0].size-1 && image[sr][sc+1]==sourceColor) resultImage = floodFill(resultImage, sr, sc+1, color)
return resultImage
}
}
0 comments:
張貼留言