1 泛洪填充算法(Flood Fill Algorithm)
泛洪填充算法(Flood Fill Algorithm) ,又称洪水填充算法,是在很多图形绘制软件中常用的填充算法,最熟悉不过就是 windows 自带画图软件的油漆桶功能。
2 源程序
using System;
using System.Collections;
using System.Collections.Generic;
namespace Legalsoft.Truffer.Algorithm
{
/// <summary>
/// 洪水填充算法
/// </summary>
public static partial class Algorithm_Gallery
{
private static void Fill_4Directions(int[,] screen, int x, int y, int prevC, int newC)
{
int M = screen.GetLength(0);
int N = screen.GetLength(1);
if (x < 0 || x >= M || y < 0 || y >= N)
{
return;
}
if (screen[x, y] != prevC)
{
return;
}
screen[x, y] = newC;
Fill_4Directions(screen, x + 1, y, prevC, newC);
Fill_4Directions(screen, x - 1, y, prevC, newC);
Fill_4Directions(screen, x, y + 1, prevC, newC);
Fill_4Directions(screen, x, y - 1, prevC, newC);
}
public static void Flood_Fill(int[,] screen, int x, int y, int newC)
{
int prevC = screen[x, y];
if (prevC == newC)
{
return;
}
Fill_4Directions(screen, x, y, prevC, newC);
}
}
}
3 代码格式
using System;
using System.Collections;
using System.Collections.Generic;namespace Legalsoft.Truffer.Algorithm
{/// <summary>/// 洪水填充算法/// </summary>public static partial class Algorithm_Gallery{private static void Fill_4Directions(int[,] screen, int x, int y, int prevC, int newC){int M = screen.GetLength(0);int N = screen.GetLength(1);if (x < 0 || x >= M || y < 0 || y >= N){return;}if (screen[x, y] != prevC){return;}screen[x, y] = newC;Fill_4Directions(screen, x + 1, y, prevC, newC);Fill_4Directions(screen, x - 1, y, prevC, newC);Fill_4Directions(screen, x, y + 1, prevC, newC);Fill_4Directions(screen, x, y - 1, prevC, newC);}public static void Flood_Fill(int[,] screen, int x, int y, int newC){int prevC = screen[x, y];if (prevC == newC){return;}Fill_4Directions(screen, x, y, prevC, newC);}}
}