λ°μν
ποΈ λ¬Έμ 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();
}
}
}
λ°μν