From dd75655ecac97886cefa86f32a70cff535c18f42 Mon Sep 17 00:00:00 2001 From: huangge1199 Date: Fri, 2 Jul 2021 15:44:40 +0800 Subject: [PATCH] =?UTF-8?q?LeetBook--=E9=98=9F=E5=88=97&=E6=A0=88--?= =?UTF-8?q?=E5=9B=BE=E5=83=8F=E6=B8=B2=E6=9F=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/leet/book/queueStack/FloodFill.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/main/java/leet/book/queueStack/FloodFill.java diff --git a/src/main/java/leet/book/queueStack/FloodFill.java b/src/main/java/leet/book/queueStack/FloodFill.java new file mode 100644 index 0000000..9b06257 --- /dev/null +++ b/src/main/java/leet/book/queueStack/FloodFill.java @@ -0,0 +1,40 @@ +package leet.book.queueStack; + +/** + * Created with IntelliJ IDEA. + * + * @author: 轩辕龙儿 + * @date: 2021/7/2 14:14 + * @Description: No Description + */ +public class FloodFill { + + public static void main(String[] args) { + Solution solution = new FloodFill().new Solution(); +// int[][] image = solution.floodFill(new int[][]{{1, 1, 1}, {1, 1, 0}, {1, 0, 1}}, 1, 1, 2); + int[][] image = solution.floodFill(new int[][]{{0, 0, 0}, {0, 1, 1}}, 1, 1, 1); + System.out.println(); + } + + class Solution { + public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { + int oldColor = image[sr][sc]; + if (oldColor != newColor) { + fill(image, sr, sc, newColor, oldColor); + } + return image; + } + + private void fill(int[][] image, int sr, int sc, int newColor, int oldColor) { + if (sr < 0 || sr >= image.length || sc < 0 || sc >= image[0].length || image[sr][sc] != oldColor) { + return; + } + image[sr][sc] = newColor; + fill(image, sr - 1, sc, newColor, oldColor); + fill(image, sr + 1, sc, newColor, oldColor); + fill(image, sr, sc - 1, newColor, oldColor); + fill(image, sr, sc + 1, newColor, oldColor); + } + } + +}