유기농배추
백준 1012: 유기농배추
풀이
BFS를 이용
소스코드
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static class Node {
int r, c;
Node(int r, int c) {
this.r = r;
this.c = c;
}
}
static int[] dr = { -1, 1, 0, 0 };
static int[] dc = { 0, 0, -1, 1 };
static Queue<Node> queue = new LinkedList<>();
static boolean[][] visited;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int tc = 1; tc <= T; tc++) {
int M = sc.nextInt();
int N = sc.nextInt();
int K = sc.nextInt();
int[][] map = new int[M][N];
visited = new boolean[M][N];
for (int i = 0; i < K; i++) {
int r = sc.nextInt();
int c = sc.nextInt();
map[r][c] = 1;
}
int cnt = 0;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (map[i][j] == 1) {
if (!visited[i][j]) {
queue.add(new Node(i, j));
visited[i][j] = true;
cnt++;
}
}
while (!queue.isEmpty()) {
Node node = queue.poll();
for (int d = 0; d < 4; d++) {
int nr = node.r + dr[d];
int nc = node.c + dc[d];
if (nr >= 0 && nr < M && nc >= 0 && nc < N && !visited[nr][nc]) {
if (map[nr][nc] == 1) {
queue.add(new Node(nr, nc));
visited[nr][nc] = true;
}
}
}
}
}
}
System.out.println(cnt);
}
}
}