[백준] P1012

동민·2021년 3월 11일
import java.util.Scanner;

public class P1012 { // Flood-Fill
	private static int[][] matrix;
	private static boolean[][] visit;
	private static int[] dx = { 0, 0, -1, 1 };
	private static int[] dy = { 1, -1, 0, 0 };
	private static int m, n;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int repeat = sc.nextInt(), answers[] = new int[repeat];
		for (int z = 0; z < repeat; z++) {
			m = sc.nextInt();
			n = sc.nextInt();
			int baechuCount = sc.nextInt();

			matrix = new int[n][m];
			visit = new boolean[n][m];

			for (int i = 0; i < baechuCount; i++) {
				int t1 = sc.nextInt(), t2 = sc.nextInt();
				matrix[t2][t1] = 1;
			}
			answers[z] = solution();
		}

		for (int answer : answers) {
			System.out.println(answer);
		}

		sc.close();
	}

	private static int solution() {
		int worm = 0;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (!visit[i][j] && matrix[i][j] == 1) {
					worm++;
					dfs(i, j);
				}
			}
		}
		return worm;
	}

	private static void dfs(int x, int y) {
		if (visit[x][y])
			return;
		for (int i = 0; i < 4; i++) {
			int newX = x + dx[i];
			int newY = y + dy[i];
			if (isValid(newX, newY) && matrix[newX][newY] == 1) {
				visit[x][y] = true;
				dfs(newX, newY);
			}
		}
	}

	private static boolean isValid(int x, int y) {
		return x < 0 || x >= n || y < 0 || y >= m ? false : true;
	}
}
profile
BE Developer

0개의 댓글