leetcode 733. Flood Fill

tech2022-10-29  104

https://leetcode.com/problems/flood-fill/

 

一、问题描述

给定一个二维数组以及一个坐标,将其置为新的值,并且将由该坐标可到达的、与其值相同的所有元素重置为新的值。

 

测试用例:

Input: image = [[1,1,1],[1,1,0],[1,0,1]] sr = 1, sc = 1, newColor = 2 Output: [[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); //右 } }

 

最新回复(0)