| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.FloodFill; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class FloodFillIterative : IFloodFill |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n * m) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="image"></param> |
| | 22 | | /// <param name="sr"></param> |
| | 23 | | /// <param name="sc"></param> |
| | 24 | | /// <param name="newColor"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public int[][] FloodFill(int[][] image, int sr, int sc, int newColor) |
| 3 | 27 | | { |
| 3 | 28 | | if (image[sr][sc] == newColor) |
| 1 | 29 | | { |
| 1 | 30 | | return image; |
| | 31 | | } |
| | 32 | |
|
| 2 | 33 | | ReplacePixels(image, sr, sc, image[sr][sc], newColor); |
| | 34 | |
|
| 2 | 35 | | return image; |
| 3 | 36 | | } |
| | 37 | |
|
| | 38 | | private static void ReplacePixels(IReadOnlyList<int[]> image, int sr, int sc, int oldColor, int newColor) |
| 50 | 39 | | { |
| 50 | 40 | | if (sr < 0 || sr >= image.Count || sc < 0 || sc >= image[sr].Length || image[sr][sc] != oldColor) |
| 38 | 41 | | { |
| 38 | 42 | | return; |
| | 43 | | } |
| | 44 | |
|
| 12 | 45 | | image[sr][sc] = newColor; |
| | 46 | |
|
| 12 | 47 | | ReplacePixels(image, sr - 1, sc, oldColor, newColor); |
| 12 | 48 | | ReplacePixels(image, sr + 1, sc, oldColor, newColor); |
| 12 | 49 | | ReplacePixels(image, sr, sc - 1, oldColor, newColor); |
| 12 | 50 | | ReplacePixels(image, sr, sc + 1, oldColor, newColor); |
| 50 | 51 | | } |
| | 52 | | } |