๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜/๋ฌธ์ œ

[์ž๋ฐ”] ๋ฐฑ์ค€ 1012 - ์œ ๊ธฐ๋† ๋ฐฐ์ถ”

by applemango2021 2020. 12. 6.

๋ฌธ์ œ๋Š” BFS๋กœ ๊ฐ„๋‹จํžˆ ํ’€๋ฆฌ๋Š”๋ฐ, N๊ณผ M์˜ ๋ฐฉํ–ฅ ๋•Œ๋ฌธ์— ํ—ท๊ฐˆ๋ฆฐ๋‹ค. 

๋‚˜๋Š” ๋ฐฐ์—ด์˜ ์‚ฌ์ด์ฆˆ๋ฅผ ๋‚˜ํƒ€๋‚ผ ๋•Œ array[n][m] ์ด๋ ‡๊ฒŒ ๋งŽ์ด ์‚ฌ์šฉํ•˜๋Š”๋ฐ, ๋”ฐ์ง€๊ณ  ๋ณด๋ฉด ์„ธ๋กœ์˜ ๊ธธ์ด๋ฅผ ๊ฐ€๋กœ์˜ ๊ธธ์ด๋ณด๋‹ค ๋จผ์ € ๋‚˜ํƒ€๋‚ด๋Š” ๊ฑฐ๋‹ค. ๊ทผ๋ฐ ๋ฌธ์ œ ์ž…๋ ฅ์—์„œ๋Š” (X,Y) ์ˆœ์œผ๋กœ ์ฃผ์–ด์ง„๋‹ค. ์ฆ‰, ์ขŒํ‘œ ํ‰๋ฉด์„ ์ƒ๊ฐํ•  ๋•Œ ๋งŽ์ด ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ฐ€๋กœ ์œ„์น˜๋ฅผ ์„ธ๋กœ ์œ„์น˜๋ณด๋‹ค ๋จผ์ € ์•Œ๋ ค์ฃผ๋Š” ๊ฒƒ! 

๋ณ„ ๊ฑฐ ์•„๋‹ ์ˆ˜๋„ ์žˆ๋Š”๋ฐ, ์ฝ”๋“œ์งค ๋•Œ Y๋ฅผ ์•ž์— ๋‘๊ณ  ์ƒ๊ฐํ• ๋ผ๋‹ˆ๊นŒ ๋ญ”๊ฐ€ ๋‚ฏ์„ค์–ด์„œ ํ—ท๊ฐˆ๋ ธ๋‹ค. N์ด M๋ณด๋‹ค ๋จผ์ € ์˜ค๋Š” ๊ฑด ํ•˜๋‚˜๋„ ์•ˆ ํ—ท๊ฐˆ๋ฆฌ๋Š”๋ฐ!

/* 2020.12.06(์ผ)*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;

public class Main1012_์œ ๊ธฐ๋†๋ฐฐ์ถ” {

	static int N, M, K;
	static boolean[][] baeju;
	static boolean[][] visited;
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		int T = Integer.parseInt(br.readLine().trim());
		for(int t=1;t<=T;t++) {
			String[] str = br.readLine().trim().split(" ");
			M = Integer.parseInt(str[0]); //๊ฐ€๋กœ๊ธธ์ด
			N = Integer.parseInt(str[1]); //์„ธ๋กœ๊ธธ์ด
			K = Integer.parseInt(str[2]);
			
			baeju = new boolean[N][M];
			visited = new boolean[N][M];
			
			int x,y;
			for(int k=0;k<K;k++) {
				str = br.readLine().trim().split(" ");
				x = Integer.parseInt(str[0]); //M์— ํ•ด๋‹น
				y = Integer.parseInt(str[1]); //N์— ํ•ด๋‹น
				
				baeju[y][x] = true;
			}
			
			int cnt = 0;
			for(int a=0;a<N;a++) {
				for(int b=0;b<M;b++) {
					if(baeju[a][b]&& !visited[a][b]) {
						cnt++;
						bfs(a,b,cnt);
					}
				}
			}
			
			sb.append(cnt+"\n");
		}
		System.out.println(sb.toString());
		
	}

	private static void bfs(int a, int b, int cnt) {
		visited[a][b] = true;
		
		Queue<int[]> que = new LinkedList<int[]>();
		que.add(new int[] {a,b});
		
		int[] tmp;
		int tmpX, tmpY, newX, newY;
		while(!que.isEmpty()) {
			tmp = que.poll();
			tmpY = tmp[0];
			tmpX = tmp[1];
			
			int[][] dir = {{1,0},{-1,0},{0,1},{0,-1}};
			for(int d=0;d<4;d++) {
				newY = tmpY + dir[d][0];
				newX = tmpX + dir[d][1];
				
				if(newY>=0 && newY<N && newX>=0 && newX<M
						&& !visited[newY][newX] && baeju[newY][newX]) {
					visited[newY][newX] = true;
					que.add(new int[] {newY, newX});
				}
			}
		}	
	}
}