[JAVA] 백준 1012 유기농배추
import java.util.*;
public class Main {
static int T;
static int M;
static int N;
static int K;
static int[][] map;
static boolean[][] visit;
static int[] dx = {0,1,0,-1};
static int[] dy = {1,0,-1,0};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
T = sc.nextInt();
for(int i=0;i<T;i++){
int cnt =0;
M = sc.nextInt();
N = sc.nextInt();
K = sc.nextInt();
map = new int[N][M];
visit = new boolean[N][M];
for(int j=0;j<K;j++){
int x = sc.nextInt();
int y = sc.nextInt();
map[y][x] = 1;
}
for(int j=0;j<N;j++){
for(int k=0;k<M;k++){
if(map[j][k]==1 && visit[j][k]==false){
dfs(j,k);
cnt++;
}
}
}
System.out.println(cnt);
}
}
public static void dfs(int yy, int xx){
visit[yy][xx]=true;
for(int i=0;i<4;i++){
int new_y = yy + dy[i];
int new_x = xx + dx[i];
if(new_y>=0 && new_x>=0 && new_y<N && new_x<M){
if(map[new_y][new_x]==1 && visit[new_y][new_x]==false){
dfs(new_y,new_x);
}
}
}
}
}