漫水填充也叫泛洪填充,是画图软件中的油漆桶功能,但在运用中,远不止于此,比如构造一个矩阵数据,需要检测边界,在边界的内外填入不同的数据。油漆桶是对图形的快速填充,将图象以位图数据的形式来看,其实也是一个矩阵数据或者说是二维数组,所以我们如果以数字作为矩阵数据,那么只需检测里面的数据即可。然后将数据再绘制成图像,那就是油漆桶的功能。为了保存数据,我们定义了一个数字矩阵,并在矩阵中实现相应的填充方法,代码如下。
#region DigitMatrix
/// <summary>
/// 数字矩阵
/// </summary>
public class DigitMatrix
{
#region 属性
/// <summary>
/// 行数
/// </summary>
public int RowCount { get; private set; }
/// <summary>
/// 列数
/// </summary>
public int ColumnCount { get; private set; }
public int[,] Data { get; private set; }
#endregion
public DigitMatrix(int rowCount, int columnCount)
{
RowCount = rowCount;
ColumnCount = columnCount;
Data = new int[RowCount, ColumnCount];
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
for (int r = 0; r < RowCount; r++)
{
string line = "";
for (int c = 0; c < ColumnCount; c++)
{
line += Data[r, c];
}
sb.AppendLine(line);
}
return sb.ToString();
}
#region FloodFill8
/// <summary>
/// 漫水填充(8邻域填充)
/// </summary>
/// <param name="r">行</param>
/// <param name="c">列</param>
/// <param name="newValue"></param>
/// <param name="oldValue"></param>
/// <param name="matrix"></param>
public void FloodFill8(int r, int c, int newValue, int oldValue)
{//递归实现可能造成堆栈溢出错误
if (r >= 0 && r < RowCount && c >= 0 && c < ColumnCount &&
Data[r, c] == oldValue && Data[r, c] != newValue)
{
Data[r, c] = newValue;
FloodFill8(r + 1, c, newValue, oldValue);
FloodFill8(r - 1, c, newValue, oldValue);
FloodFill8(r, c + 1, newValue, oldValue);
FloodFill8(r, c - 1, newValue, oldValue);
FloodFill8(r + 1, c + 1, newValue, oldValue);
FloodFill8(r - 1, c - 1, newValue, oldValue);
FloodFill8(r - 1, c + 1, newValue, oldValue);
FloodFill8(r + 1, c - 1, newValue, oldValue);
}
}
#endregion
#region FloodFill8WithStac