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

입력
첫 번째 줄에는 지도의 크기 N(정사각형이므로 가로와 세로의 크기는 같으며 5≤N≤25)이 입력되고, 그 다음 N줄에는 각각 N개의 자료(0혹은 1)가 입력된다.
출력
첫 번째 줄에는 총 단지수를 출력하시오. 그리고 각 단지내 집의 수를 오름차순으로 정렬하여 한 줄에 하나씩 출력하시오.
예제 입력 1
7
0110100
0110101
1110101
0000111
0100000
0111110
0111000
예제 출력 1
3
7
8
9
BFS를 선택한 이유
내 느낌으로는 어떤 특정 경로(도착점)을 찾는게 아니라 단지의 전체 크기를 구해야 하기 때문에 가까운 노드부터 탐색해 나가는 BFS가 효율적으로 보였다.
이 문제를 예전에 파이썬으로 풀어본적 있다. 그때는 사실 DFS,BFS에 대한 공부가 되어 있지 않은 상태에서 다른 사람의 코드를 보고 이해를 하고 넘겼는데, 이번에는 혼자 작성해봤다.
정답 코드 :)
1. 변수 선언 & 입력값 받기
- 변수는 bfs함수에서도 컨트롤해야하기 때문에 static으로 선언
- dx,dy는 현재 좌표에서 상하좌우로 노드를 옮겨 같은 단지인지 아닌지 판단할때 쓴다.
- Queue는 bfs를 위해
import java.io.*;
import java.util.*;
public class Main {
static int total = 0; //단지수
static int N; //지도의 크기
static int[][] map; //지도 배열
static int size; //집의 크기
static int[] dx = {1, 0, -1, 0}; //x방향으로 탐색
static int[] dy = {0, 1, 0, -1}; //y방향으로 탐색
static Queue<Integer[]> queue = new LinkedList<>();
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
map = new int[N][N];
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < N; i++) {
String s = br.readLine();
String[] str = s.split("");
for (int j = 0; j < N; j++) {
map[i][j] = Integer.parseInt(str[j]);
}
}
}
2. bfs함수 호출 & 결과값 출력
- for문을 타고 각 노드를 조사한다. map에 1이 있으면 조사 시작
- 단지의 크기는 0으로 초기화하고, total (단지 수) 를 +1
- bfs에서 size를 계산해주고, list에 더해준다.
- 마지막에는 오름차순으로 출력
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (map[i][j] == 1) {
size = 0;
total++;
bfs(i, j);
list.add(size);
}
}
}
System.out.println(total);
int[] result = list.stream().mapToInt(i -> i).toArray();
Arrays.sort(result);
for (int i : result) {
System.out.println(i);
}
3. bfs 함수
노드의 좌표가 1일때 bfs를 출력헀다. 좌표를 큐에 넣고 0으로 바꿔주고, size는 +1.
큐에서 poll을 해서 cx,cy로 현재좌표를 저장하고, for문을 통해 dx,dy를 더해줘서 각각 상하좌우의 노드가 1인지 판단하고 , 큐에 넣어준다.
static void bfs(int x, int y) {
queue.add(new Integer[]{x, y});
map[x][y] = 0;
size++;
while (!queue.isEmpty()) {
Integer[] element = queue.poll();
int cx = element[0];
int cy = element[1];
for (int i = 0; i < 4; i++) {
int nx = cx + dx[i];
int ny = cy + dy[i];
if (nx >= 0 && ny >= 0 && nx < N && ny < N && map[nx][ny] == 1) {
queue.add(new Integer[]{nx, ny});
map[nx][ny] = 0;
size++;
}
}
}
}
4. 전체코드
import java.io.*;
import java.util.*;
public class Main {
static int total = 0; //단지수
static int N; //지도의 크기
static int[][] map; //지도 배열
static int size; //집의 크기
static int[] dx = {1, 0, -1, 0}; //x방향으로 탐색
static int[] dy = {0, 1, 0, -1}; //y방향으로 탐색
static Queue<Integer[]> queue = new LinkedList<>();
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
map = new int[N][N];
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < N; i++) {
String s = br.readLine();
String[] str = s.split("");
for (int j = 0; j < N; j++) {
map[i][j] = Integer.parseInt(str[j]);
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (map[i][j] == 1) {
size = 0;
total++;
bfs(i, j);
list.add(size);
}
}
}
System.out.println(total);
int[] result = list.stream().mapToInt(i -> i).toArray();
Arrays.sort(result);
for (int i : result) {
System.out.println(i);
}
}
static void bfs(int x, int y) {
queue.add(new Integer[]{x, y});
map[x][y] = 0;
size++;
while (!queue.isEmpty()) {
Integer[] element = queue.poll();
int cx = element[0];
int cy = element[1];
for (int i = 0; i < 4; i++) {
int nx = cx + dx[i];
int ny = cy + dy[i];
if (nx >= 0 && ny >= 0 && nx < N && ny < N && map[nx][ny] == 1) {
queue.add(new Integer[]{nx, ny});
map[nx][ny] = 0;
size++;
}
}
}
}
}
마무리
BFS 혼자 할 수 있어서 뿌듯했음
'알고리즘 > BFS' 카테고리의 다른 글
[ BFS ] 백준 2178번 미로 탐색 (0) | 2024.07.26 |
---|