-
Q. 2667 자바 : 단지번호붙이기코딩테스트/백준_Java 2023. 3. 29. 13:35
Q. 2667 자바 : 단지번호붙이기
문제 : boj.kr/2667
실버 1 난이도의 문제이다.
0과 1로 구성된 격자형 그래프가 주어지고, 1(=집을 의미)이 모여 있는 곳을 단지로 정의했을 때,
단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 문제이다.
지도의 크기 N이 주어지는데, 격자형 그래프 순회 문제의 경우 모든 점을 순회해야 하므로 시간 복잡도는 O(N^2)이고,문제에서N의 최대값은 25이므로
시간초과는 걱정하지 않아도 된다.
또한 입력을 받을 때 자료형은 0과 1로만 구분되므로 boolean을 사용했다.
문제를 푼 방식은
1. 탐색이 가능한 경우(arr[y][x] = true) 방문하고, 이후에 탐색을 진행하며 방문 횟수를 저장한다.
(이 때 방문한 경우 방문한 곳에 대한 표시는 반드시 해야 한다.(arr[y][x] = false))
2. 그리고 한 단지에 대해 탐색이 끝난 경우 그 값을 ArrayList에 저장한다.
3. 이후 전체 탐색이 끝났을 때 ArrayList의 크기가 단지의 개수이므로,
ArrayLIst를 먼저 출력하고 정렬된 ArrayList 값을 하나씩 출력한다.
문제에서 주의해야 할 점으로는 각 단지내 집의 수를 오름차순으로 정렬하여 한 줄에 하나씩 출력하라 했으므로
위에서 모든 탐색이 끝난 뒤에 단지를 저장한 ArrayList를 정렬해야 한다.
시간복잡도를 계산하면
1. 격자형 그래프 순회 - O(N^2)
2. 단지의 수 정렬의 최악의 경우 (체스판 모양의 단지가 생성된 경우) - O(N / 2)
3. 단지의 수가 저장된 List 정렬 - 약O(N log N)
따라서 약 O(N^2)의시간복잡도가 나오게 된다. 따라서 위 문제를 푸는데는 지장이 없다.
그래프 탐색 문제들의 경우 특수한 경우를 제외하고는 bfs, dfs 두 방식 모두 사용 가능하므로 두 방식을 통해서 풀었다.bfs를 사용한 풀이
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class Main { static FastReader scan = new FastReader(); static StringBuilder sb = new StringBuilder(); static int N, cnt = 0, cur = 0; static boolean[][] arr; static int[] dy = new int[]{0, 1, 0, -1}; static int[] dx = new int[]{1, 0, -1, 0}; static List<Integer> houseCnt; static void input() { N = scan.nextInt(); arr = new boolean[N][N]; for (int i = 0; i < N; i++) { char[] input = scan.next().toCharArray(); for (int j = 0; j < N; j++) { if (input[j] == '1') arr[i][j] = true; } } } static void bfs(int y, int x) { Queue<int[]> que = new LinkedList<>(); /* TODO */ arr[y][x] = false; que.add(new int[]{y, x}); int cnt = 1; while (!que.isEmpty()) { int[] point = que.poll(); for (int i = 0; i < 4; i++) { int nextY = point[0] + dy[i]; int nextX = point[1] + dx[i]; if (nextX == -1 || nextX == N || nextY == -1 || nextY == N) continue; if (arr[nextY][nextX]) { cnt++; que.add(new int[]{nextY, nextX}); arr[nextY][nextX] = false; } } } houseCnt.add(cnt); } static void pro() { houseCnt = new ArrayList<>(); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (arr[i][j]) bfs(i, j); } } Collections.sort(houseCnt); sb.append(houseCnt.size()).append('\n'); for (int i: houseCnt) { sb.append(i).append('\n'); } System.out.println(sb); } public static void main(String[] args) { input(); pro(); } static class FastReader { // BufferedReader의 빠른 속도, // + Scanner의 타입별 입력값을 받는 기능을 혼합 // (자바 내부에 구현된 Scanner는 속도가 느림) // 다른분의 코드를 참고한 코드 BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
dfs를 이용한 풀이
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class Main { static FastReader scan = new FastReader(); static StringBuilder sb = new StringBuilder(); static int N, cnt = 0; static boolean[][] arr; static int[] dy = new int[]{0, 1, 0, -1}; static int[] dx = new int[]{1, 0, -1, 0}; static List<Integer> houseCnt; static void input() { N = scan.nextInt(); arr = new boolean[N][N]; for (int i = 0; i < N; i++) { char[] input = scan.next().toCharArray(); for (int j = 0; j < N; j++) { if (input[j] == '1') arr[i][j] = true; } } houseCnt = new ArrayList<>(); } static void dfs(int y, int x) { cnt++; arr[y][x] = false; for (int i = 0; i < 4; i++) { int nextY = y + dy[i]; int nextX = x + dx[i]; if (nextX == -1 || nextX == N || nextY == -1 || nextY == N) continue; if (arr[nextY][nextX]) { dfs(nextY, nextX); } } } static void pro() { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (arr[i][j]) { cnt = 0; dfs(i, j); houseCnt.add(cnt); } } } Collections.sort(houseCnt); sb.append(houseCnt.size()).append('\n'); for (int i: houseCnt) { sb.append(i).append('\n'); } System.out.println(sb); } public static void main(String[] args) { input(); pro(); } static class FastReader { // BufferedReader의 빠른 속도, // + Scanner의 타입별 입력값을 받는 기능을 혼합 // (자바 내부에 구현된 Scanner는 속도가 느림) // 다른분의 코드를 참고한 코드 BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
반응형'코딩테스트 > 백준_Java' 카테고리의 다른 글
Q. 11724 자바 : 연결 요소의 개수 (0) 2023.03.31 Q. 1012 자바 : 유기농 배추 (0) 2023.03.30 Q. 1260 자바 : DFS와 BFS (0) 2023.03.28 Q. 20366 자바 : 같이 눈사람 만들래? (0) 2023.03.27 Q.11559 자바 : Puyo Puyo(G4) (0) 2023.01.10