백준 알고리즘 기초 2/그래프 1

[백준] 2667 : 단지번호붙이기(BFS)

STUDYING,,, 2021. 10. 1. 14:50

알고리즘 기초 2 / 2

DAY - 2

https://www.acmicpc.net/problem/2667

 

2667번: 단지번호붙이기

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여

www.acmicpc.net

문제

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.


그래프문제를 BFS, DFS로 둘다 풀어보았다. 실버1 문제여서 그런지 크게 어려움을 느끼지는 않았다. 다만 코딩을 할 때 더욱 섬세하게 코딩을 해야할 필요성과 계획에 중요성을 다시 느끼게 되었다..

package day1001;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;

public class Baekjoon_2667_단지번호붙이기_BFS {

	static int[][] map;
	static boolean[][] visit;
	static ArrayList<Integer> list;
	static int N, cnt;
	static int[] dx = { 0, 0, 1, -1 };
	static int[] dy = { 1, -1, 0, 0 };

	public static void main(String[] args) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		N = Integer.parseInt(br.readLine());			
		map = new int[N][N];
		visit = new boolean[N][N];

		for (int i = 0; i < N; i++) {
			String str = br.readLine();
			for (int j = 0; j < N; j++) {
				map[i][j] = str.charAt(j) - '0';
			}
		}
		cnt = 0;
		list = new ArrayList<>();
		
        for (int i = 0; i < map.length; i++) {
			for (int j = 0; j < map[i].length; j++) {
				if (map[i][j] == 1 && !visit[i][j]) 
					bfs(i, j);			
			}
		}
		Collections.sort(list);

		System.out.println(cnt);
		for (int a : list) {
			System.out.println(a);
		}
		br.close();
	}

	private static void bfs(int i, int j) {

		Queue<point> que = new LinkedList<>();
		int houseCnt = 1;

		que.offer(new point(i, j));
		visit[i][j] = true;
		while (!que.isEmpty()) {

			point tmp = que.poll();
			for (int k = 0; k < 4; k++) {

				int nx = tmp.x + dx[k];
				int ny = tmp.y + dy[k];

				if (nx < 0 || ny < 0 || nx >= N || ny >= N)
					continue;

				if (map[nx][ny] == 1 && !visit[nx][ny]) {
					visit[nx][ny] = true;
					que.add(new point(nx, ny));
					houseCnt++;
				}
			}
		}
		cnt++;
		list.add(houseCnt);
	}
}

class point {
	int x;
	int y;
	point(int x, int y) {
		this.x = x;
		this.y = y;
	}
}