๐ฐ๐๐๐๐๐๐๐๐/๐ฑ๐๐๐๐๐๐๐
[๋ฐฑ์ค/Java] ์ ๊ธฐ๋ ๋ฐฐ์ถ 1012
ํด๋ฒ๋
2023. 12. 19. 09:51
๋ฐ์ํ
๋ฌธ์
https://www.acmicpc.net/problem/1012
1012๋ฒ: ์ ๊ธฐ๋ ๋ฐฐ์ถ
์ฐจ์ธ๋ ์๋์ธ ํ๋๋ ๊ฐ์๋ ๊ณ ๋ญ์ง์์ ์ ๊ธฐ๋ ๋ฐฐ์ถ๋ฅผ ์ฌ๋ฐฐํ๊ธฐ๋ก ํ์๋ค. ๋์ฝ์ ์ฐ์ง ์๊ณ ๋ฐฐ์ถ๋ฅผ ์ฌ๋ฐฐํ๋ ค๋ฉด ๋ฐฐ์ถ๋ฅผ ํด์ถฉ์ผ๋ก๋ถํฐ ๋ณดํธํ๋ ๊ฒ์ด ์ค์ํ๊ธฐ ๋๋ฌธ์, ํ๋๋ ํด์ถฉ ๋ฐฉ์ง์
www.acmicpc.net
ํ์ด
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class Main {
public static boolean[][] visited; // ๋ฐฉ๋ฌธ ์ฌ๋ถ
public static int[][] graph;
public static int count;
public static int[] dx = {0, -1, 0, 1};
public static int[] dy = {-1, 0, 1, 0};
/**
* ์ํ์ข์ฐ๋ก ์ด์ด์ ธ ์์ผ๋ฉด ํ์
*
* @param x
* @param y
*/
public void dfs(int x, int y) {
visited[x][y] = true;
for (int i = 0; i < 4; i++) {
int cx = x + dx[i];
int cy = y + dy[i];
if (cx >= 0 && cy >= 0 && cx < graph.length && cy < graph[0].length) {
if (graph[cx][cy] == 1 && visited[cx][cy] == false) {
dfs(cx, cy);
}
}
}
}
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Main mm = new Main();
int T = Integer.parseInt(br.readLine()); // ํ
์คํธ์ผ์ด์ค ์
for (int i = 0; i < T; i++) {
count = 0;
StringTokenizer st = new StringTokenizer(br.readLine());
int m = Integer.parseInt(st.nextToken());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
graph = new int[n + 1][m + 1];
visited = new boolean[n + 1][m + 1];
for (int j = 0; j < graph.length; j++) {
for (int l = 0; l < graph[0].length; l++) {
visited[j][l] = false; // ๋ฐฉ๋ฌธ์ฌ๋ถ ์ด๊ธฐํ
}
}
for (int j = 0; j < k; j++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
graph[b][a] = 1;
}
for (int j = 0; j < graph.length; j++) {
for (int l = 0; l < graph[0].length; l++) {
if (visited[j][l] == false && graph[j][l] == 1) {
mm.dfs(j, l);
count++;
}
}
}
bw.write(String.valueOf(count) + "\n");
}
bw.flush();
bw.close();
}
}
์ ๋ต
๋ฐ์ํ