Pim*_*eko 7 c# stack-overflow algorithm recursion fill
我正在尝试制作一个可以在c#中填充int数组的算法.基本上,作为MS Paint中的填充工具,我有一个颜色,如果我在数组中选择(x,y)坐标,它会用新颜色替换所有具有相同初始颜色的邻居.
例如:
[0,0,0]
[0,1,0]
[1,1,0]
Run Code Online (Sandbox Code Playgroud)
如果我将3放入(0,0),则数组变为:
[3,3,3]
[3,1,3]
[1,1,3]
Run Code Online (Sandbox Code Playgroud)
所以我在递归中尝试了它,它确实有效,但不是所有时间.实际上,我有时会出现"Stack Overflow"错误(似乎合适).这是我的代码,如果你能告诉我什么是错的话会很棒:)
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;
}
Run Code Online (Sandbox Code Playgroud)
谢谢 !
如何使用堆栈/队列来管理剩余的工作?
public void Fill(int[,] array, int x, int y, int newInt)
{
int initial = array[x,y];
Queue<Tuple<int,int>> queue = new Queue<Tuple<int,int>>();
queue.Push(new Tuple<int, int>(x, y));
while (queue.Any())
{
Tuple<int, int> point = queue.Dequeue();
if (array[point.Value1, point.Value2] != initial)
continue;
array[point.Value1, point.Value2] = newInt;
EnqueueIfMatches(array, queue, point.Value1 - 1, point.Value2, initial);
EnqueueIfMatches(array, queue, point.Value1 + 1, point.Value2, initial);
EnqueueIfMatches(array, queue, point.Value1, point.Value2 - 1, initial);
EnqueueIfMatches(array, queue, point.Value1, point.Value2 + 1, initial);
}
}
private void EnqueueIfMatches(int[,] array, Queue<Tuple<int, int>> queue, int x, int y, int initial)
{
if (x < 0 || x >= array.GetLength(0) || y < 0 || y >= array.GetLength(1))
return;
if (array[x, y] == initial)
queue.Enqueue(new Tuple<int, int>(x, y));
}
Run Code Online (Sandbox Code Playgroud)