본문 바로가기

라이브러리/JAVA

BFS

전처리

static int[] dx = {0, 0, -1, 1};
static int[] dy = {-1, 1, 0, 0};

static class Pair
{
    int x, y;

    Pair () {}
    Pair (int x, int y) { this.x = x; this.y = y; }
}

 

2차원 BFS

static void BFS (int N, int M, int first_x, int first_y, int[][] G)
{
    Queue<Pair> Q = new LinkedList<>();
    Q.add(new Pair(first_x, first_y));
    G[first_x][first_y] = 0;

    while ( !Q.isEmpty() )
    {
        Pair p = Q.poll();

        int x = p.x;
        int y = p.y;

        for (int i=0; i<4; i++)
        {
            int temp_x = x + dx[i];
            int temp_y = y + dy[i];

            if ( temp_x < 0 || temp_x >= N
                    || temp_y < 0 || temp_y >= M
                    || G[temp_x][temp_y] == 0 )
                continue;

            Q.add(new Pair(temp_x, temp_y));
            G[temp_x][temp_y] = 0;
        }
    }
}

'라이브러리 > JAVA' 카테고리의 다른 글

트리의 지름  (0) 2024.06.23
2^N  (0) 2024.06.21
nPr, nCr, 중복조합  (1) 2024.06.18
위상 정렬  (1) 2024.06.18
GCD, LCM  (0) 2024.02.27