本文共 1020 字,大约阅读时间需要 3 分钟。
给定一个二维数组以及一个坐标,将其置为新的值,并且将由该坐标可到达的、与其值相同的所有元素重置为新的值。
测试用例:
Input:image = [[1,1,1],[1,1,0],[1,0,1]]sr = 1, sc = 1, newColor = 2Output:[[2,2,2],[2,2,0],[2,0,1]]
class Solution { public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { if (image == null || image.length == 0) { return image; } int oldColor = image[sr][sc]; if (oldColor != newColor) { dfs(image, sr, sc, oldColor, newColor); } return image; } private void dfs(int[][] image, int sr, int sc, int oldColor, int newColor) { if (sr < 0 || sr >= image.length || sc < 0 || sc >= image[0].length || image[sr][sc] != oldColor || oldColor == newColor) { return; } image[sr][sc] = newColor; dfs(image, sr-1, sc, oldColor, newColor); //上 dfs(image, sr+1, sc, oldColor, newColor); //下 dfs(image, sr, sc-1, oldColor, newColor); //左 dfs(image, sr, sc+1, oldColor, newColor); //右 }}
转载地址:http://afnii.baihongyu.com/