我认为二维数组是一个坐标,并尝试找到一个值为 1 的坐标值。
到目前为止,这是一个非常简单的 BFS 问题,但我想做的是看下图。
当我在寻找 1 或在我找到它之后,我想知道边界周围的坐标值按箭头或其他方向的顺序。
我需要添加哪些选项来获取这些信息?
下面是我现在使用的 BFS 代码。我可以从 BFS 函数中获取坐标值,如第二张图片所示。
class Node
{
public int x;
public int y;
public Node(int x, int y)
{
this.x = x;
this.y = y;
}
};
private int[] dx = new int[8] { -1, 0, 1, 0, 1, -1, -1, 1 };
private int[] dy = new int[8] { 0, -1, 0, 1, 1, -1, 1, -1 };
private Queue<Node> q = new Queue<Node>();
bool[,] visit = new bool[15, 15];
int[,] coordinates = new int[15, 15] { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0 },
{ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 },
{ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }};
void BFS(int[,] pixel, int x, int y)
{
q.Enqueue(new Node(x, y));
visit[x, y] = true;
while (q.Count != 0)
{
Node cur = q.Dequeue();
for (int i = 0; i < 8; i++)
{
int r = cur.x + dx[i];
int c = cur.y + dy[i];
if (r >= 0 && c >= 0 && r < 15 && c < 15)
{
if (!visit[r, c] && pixel[r, c] == 1)
{
q.Enqueue(new Node(r, c));
visit[r, c] = true;
}
}
}
}
}
void main()
{
for (int y = 0; y < 15; y++)
{
for (int x = 0; x < 15; x++)
{
if (!visit[x, y] && coordinates[x, y] == 1)
{
BFS(coordinates, x, y);
}
}
}
}
