C# - Flood Fill

Dev_Jen
|2025. 7. 13. 23:56
λ°˜μ‘ν˜•

πŸ–ŒοΈ 문제 733. Flood Fill

πŸ”Έ 문제 μ„€λͺ…

2차원 λ°°μ—΄ imageκ°€ μ£Όμ–΄μ§€κ³ ,

μ–΄λ–€ **μ‹œμž‘ μ’Œν‘œ (sr, sc)**와 μƒˆλ‘œμš΄ 색상 newColorκ°€ μ£Όμ–΄μ‘Œμ„ λ•Œ,

μ‹œμž‘ μ’Œν‘œμ—μ„œ μ—°κ²°λœ 같은 μƒ‰μƒμ˜ 픽셀듀을 λͺ¨λ‘ μ°Ύμ•„μ„œ,

ν•΄λ‹Ή 픽셀듀을 newColor둜 λ°”κΎΈλŠ” Flood Fill μ•Œκ³ λ¦¬μ¦˜μ„ κ΅¬ν˜„ν•˜λΌλŠ” λ¬Έμ œμ•Ό.


πŸ”Ή μž…λ ₯

  • image: 2차원 λ°°μ—΄ (각 μ›μ†ŒλŠ” 색상을 μ˜λ―Έν•˜λŠ” μ •μˆ˜)
  • sr, sc: μ‹œμž‘ ν”½μ…€μ˜ ν–‰(row), μ—΄(column)
  • newColor: λ°”κΏ€ 색상 (μ •μˆ˜)

πŸ”Ή 쑰건

  • μ—°κ²°λœ 픽셀은 μƒν•˜μ’Œμš°λ‘œ μΈμ ‘ν•˜λ©΄μ„œ 같은 색을 κ°€μ§„ ν”½μ…€λ§Œ 포함됨
  • λŒ€κ°μ„ μ€ ν¬ν•¨λ˜μ§€ μ•ŠμŒ ❌

πŸ§ͺ μ˜ˆμ‹œ

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]]

μ„€λͺ…:

  • μ‹œμž‘μ  (1,1)의 색은 1
  • 이 색과 μ—°κ²°λœ μƒν•˜μ’Œμš° λ°©ν–₯의 픽셀을 μ°Ύμ•„μ„œ 2둜 λ°”κΏˆ
  • image[2][2]은 색이 1μ΄μ§€λ§Œ μ—°κ²°λ˜μ§€ μ•Šμ•˜κΈ° λ•Œλ¬Έμ— μ œμ™Έ

🎯 λͺ©ν‘œ

μ‹œμž‘μ κ³Ό μ—°κ²°λœ λͺ¨λ“  같은 μƒ‰μ˜ 픽셀을 μ°Ύμ•„μ„œ, λͺ¨λ‘ newColor둜 λ°”κΎΌ 2차원 배열을 λ¦¬ν„΄ν•˜λŠ” ν•¨μˆ˜ κ΅¬ν˜„ν•˜κΈ°!


πŸ’‘ 핡심 κ°œλ…

  • Flood Fill은 λŒ€ν‘œμ μΈ κ·Έλž˜ν”„ 탐색 λ¬Έμ œμ•Ό.
  • 방식은 DFS(깊이 μš°μ„  탐색) λ˜λŠ” BFS(λ„ˆλΉ„ μš°μ„  탐색) 쀑 ν•˜λ‚˜λ₯Ό μ‚¬μš©ν•΄ κ΅¬ν˜„ν•  수 μžˆμ–΄.
  • DFSκ°€ κ°„λ‹¨ν•˜κ³  κ΅¬ν˜„λ„ μ‰¬μ›Œμ„œ 자주 μ‚¬μš©λΌ.
public class Program
{
    public static void Main(string[] args)
    {
        // 이미지 λ°°μ—΄ μ˜ˆμ‹œ μ„ μ–Έ (2차원 λ°°μ—΄)
        int[][] image = new int[][]
        {
            new int[] {1, 1, 1},
            new int[] {1, 1, 0},
            new int[] {1, 0, 1}
        };

        // μ‹œμž‘ μœ„μΉ˜μ™€ μƒˆ 색상 μ •μ˜
        int sr = 1;
        int sc = 1;
        int newColor = 2;

        Console.WriteLine("Before Flood Fill:");
        PrintImage(image);

        FloodFill(image, sr, sc, newColor);

        Console.WriteLine("\\nAfter Flood Fill:");
        PrintImage(image);
    }

    public static void FloodFill(int[][] image, int sr, int sc, int newColor)
    {
        int originalColor = image[sr][sc];

        if (originalColor == newColor)
        {
            return;
        }

        void Fill(int row, int col)
        {
            if (row < 0 || row >= image.Length || col < 0 || col >= image[0].Length)
                return;

            if (image[row][col] != originalColor)
                return;

            image[row][col] = newColor;

            Fill(row - 1, col); // μœ„
            Fill(row + 1, col); // μ•„λž˜
            Fill(row, col - 1); // μ™Όμͺ½
            Fill(row, col + 1); // 였λ₯Έμͺ½
        }

        Fill(sr, sc);
    }

    public static void PrintImage(int[][] image)
    {
        for (int i = 0; i < image.Length; i++)
        {
            for (int j = 0; j < image[i].Length; j++)
            {
                Console.Write(image[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
}

λ°˜μ‘ν˜•