
我需要在我使用C#的扫雷船的渲染中,打开用户选择的单元格。用户输入坐标I.1,3,程序“打开”该单元格,它要么显示一个指示其周围炸弹的数字,要么显示一个空字段(如扫雷器!)。我应该如何解决这个问题,使细胞和它附近的每个细胞打开,如果是空的?
//Opens cells if there is no bomb
public bool Open(int row, int column)
{
bool result = false;
if (row >= 0 && row < Dimension && column >= 0 && column < Dimension)
{
if (!cells[row, column].Open)
{
cells[row, column].Open = true;
result = true;
}
}
return result;
}“”“
发布于 2022-09-12 02:30:39
最简单的解决方案是递归调用每个相邻单元的Open函数。由于Open函数已经检查无效/打开单元格,因此无需在递归调用之前进行预检查。
if (cells[row, column].Empty)
{
Open(row - 1, column - 1);
Open(row - 1, column);
Open(row - 1, column + 1);
Open(row, column - 1);
Open(row, column + 1);
Open(row + 1, column - 1);
Open(row + 1, column);
Open(row + 1, column + 1);
}如果需要非递归方法,则可以使用宽度优先搜索之类的方法。
public bool Open(int row, int column)
{
bool result = false;
if (row >= 0 && row < Dimension && column >= 0 && column < Dimension)
{
if (!cells[row, column].Open)
{
cells[row, column].Open = true;
if (cells[row, column].Empty)
{
var bfs = new Queue<(int Row, int Column)>()
bfs.Enqueue((row, column));
while (bfs.Count > 0)
{
(int r, int c) = bfs.Dequeue();
int rb = r - 1;
if (rb < 0) rb = r;
int re = r + 1;
if (re >= Dimension) re = r;
int cb = c - 1;
if (cb < 0) cb = c;
int ce = c + 1;
if (ce >= Dimension) ce = c;
for (int i = rb; i <= re; i++)
{
for (int j = cb; j <= ce; j++)
{
if (!cells[i, j].Open)
{
cells[i, j].Open = true;
if (cells[i, j].Empty) bfs.Enqueue((i, j));
}
}
}
}
}
result = true;
}
}
return result;
}https://stackoverflow.com/questions/73683936
复制相似问题