전처리
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;
}
}
}