洪水填充【难度:3级】:
答案1:
using System;
using System.Collections.Generic;
using System.Linq;
public class Kata
{
struct Coord
{
public int x;
public int y;
public Coord(int x, int y)
{
this.x = x;
this.y = y;
}
}
public static int[,] FloodFill(int[,] array, int y, int x, int newValue)
{
if ((y < 0 || x < 0) || array[y, x] == newValue) return array;
Stack<Coord> stack = new Stack<Coord>();
stack.Push(new Coord(x, y));
int valueToFill = array[y, x];
Coord current;
do
{
current = stack.Peek();
array[current.y, current.x] = newValue;
if (current.x - 1 >= 0 && array[current.y, current.x - 1] == valueToFill)
{
stack.Push(new Coord(current.x - 1, current.y));
} else if (current.x + 1 < array.GetLength(1) && array[current.y, current.x + 1] == valueToFill)
{
stack.Push(new Coord(current.x + 1, current.y));
} else if (current.y - 1 >= 0 && array[current.y - 1, current.x] == valueToFill)
{
stack.Push(new Coord(current.x, current.y - 1));
}else if (current.y + 1 < array.GetLength(0) && array[current.y + 1, current.x] == valueToFill)
{
stack.Push(new Coord(current.x, current.y + 1));
}else
{
stack.Pop();
}
} while (stack.Count > 0);
return array;
}
}
答案2:
using System;
using System.Collections.Generic;
public class Kata
{
public static int[,] FloodFill(int[,] array, int x, int y, int newValue)
{
var areaValue = array[x,y];
var s = new Stack<Tuple<int, int>>();
s.Push(new Tuple<int, int>(x, y));
while (s.Count > 0)
{
var point = s.Pop();
var p_x = point.Item1;
var p_y = point.Item2;
if (array[p_x,p_y] != areaValue || array[p_x,p_y] == newValue)
continue;
array[p_x,p_y] = newValue;
if (p_x > 0)
s.Push(new Tuple<int, int>(p_x - 1, p_y));
if (p_x < array.GetUpperBound(0))
s.Push(new Tuple<int, int>(p_x + 1, p_y));
if (p_y > 0)
s.Push(new Tuple<int, int>(p_x, p_y - 1));
if (p_y < array.GetUpperBound(1))
s.Push(new Tuple<int, int>(p_x, p_y + 1));
}
return array;
}
}
答案3:
using System;
using System.Linq;
using System.Collections.Generic;
public class Kata
{
public static int[,] FloodFill(int[,] a, int x, int y, int n)
{
int lx=a.GetLength(0),ly=a.GetLength(1),m=a[x,y],ct=-1;
var rs1=new List<int[]>();
a[x,y]=-1;
rs1.Add(new int[]{
x,y});
while(ct!=rs1.Count){
ct=rs1.Count;
for (int i=0;i<rs1.Count;i++){
int cx=rs1[i][0] , cy=rs1[i][1];
int xup=(cx==0 ? 0 : cx-1) , xdn=(cx==lx-1 ? cx : cx+1) , yup=(cy==0 ? 0 : cy-1