如何使用bfs算法查找边界点

Han*_*Kim 1 algorithm breadth-first-search

我将2D数组视为一个坐标,并尝试查找值为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);
            }
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

Bis*_*alG 5

我们不需要BFS查找边界' 1'值。我们可以简单地在2D网格上循环,然后对于每个' 1',我们只需检查它的4个相邻(i.e up, down, left, right)值是否全部为' 1'。如果其中至少一个不是' 1',则为边界点。谢谢!