我需要在2D数组中找到具有相同数字的最大区域。例如:{{ 2 2 3} {1 2 3} {1 2 1}}
并在新的2D数组中用相同的数字标记相同的区域。
我需要用3种颜色为表格着色,所以我在表格中使用1-3之间[,]
我做了测试,但是无法正常工作。 ID只会在同一区域堆叠太多。
第二次修改:更新了代码
public class Matrix
{
public int Height { get; set; }
public int Witdh { get; set; }
public int[,] Table { get; set; }
public int[,] Area { get; set; }
public int ID { get; set; }
public int tempBiggestArea = 0;
public int biggestArea { get; set; }
public Matrix(int height, int witdh)
{
Table = GenerateTable(height, witdh);
Height = height;
Witdh = witdh;
ID = 2;
Area = new int[height,witdh];
}
public int[,] GenerateTable(int height, int witdh)
{
int[,] table = new int[height, witdh];
Random rnd = new Random();
for (int i = 0; i < table.GetLength(0); i++)
{
for (int j = 0; j < table.GetLength(1); j++)
{
table[i, j] = rnd.Next(3) + 1;
}
}
return table;
}
public void Find(int x, int y, int color)
{
if (y < 0)
y = Height - 1;
if (x < 0)
x = Witdh - 1;
if (IsChanged(x, y))
return;
if (Area[x, y] == 0)
{
if (color > 3)
color = 1;
if (Table[x, y] == color)
{
Area[x, y] = ID;
tempBiggestArea++;
Find(x, y - 1, color);
Find(x - 1, y, color);
ID++;
}
}
if (tempBiggestArea > biggestArea)
biggestArea = tempBiggestArea;
tempBiggestArea = 0;
Find(x, y, color + 1);
}
public bool IsChanged(int i, int j)
{
return Area[i, j] != 0;
}