【发布时间】:2014-02-16 23:20:24
【问题描述】:
我正在尝试制作一种可以在 c# 中填充 int 数组的算法。基本上,作为 MS Paint 中的填充工具,我有一种颜色,如果我在数组中选择 (x,y) 坐标,它会用新颜色替换所有具有相同初始颜色的邻居。
例如:
[0,0,0]
[0,1,0]
[1,1,0]
如果我将 3 放入 (0,0),则数组变为:
[3,3,3]
[3,1,3]
[1,1,3]
所以我尝试了递归,它确实有效,但并非一直有效。实际上,我有时会遇到“堆栈溢出”错误(似乎合适)。 这是我的代码,如果你能告诉我出了什么问题,那就太好了:)
public int[,] fill(int[,] array, int x, int y, int initialInt, int newInt)
{
if (array[x, y] == initialInt)
{
array[x, y] = newInt;
if (x < array.GetLength(0) - 1)
array = fill(array, (x + 1), y, initialInt, newInt);
if (x > 0)
array = fill(array, (x - 1), y, initialInt, newInt);
if (y < array.GetLength(1) - 1)
array = fill(array, x, (y + 1), initialInt, newInt);
if (y > 0)
array = fill(array, x, (y - 1), initialInt, newInt);
}
return array;
}
谢谢!
【问题讨论】:
-
是的......这是一个递归调用的废话。可能最好以 C# 之类的语言以程序方式执行此操作,该语言不能保证尾调用优化(并不是说您当前的代码无论如何都会从中受益)
-
不错 -->“堆栈溢出”
标签: c# algorithm recursion fill stack-overflow