티스토리 뷰
문제
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집들의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여기서 연결되었다는 것은 어떤 집이 좌우, 혹은 아래위로 다른 집이 있는 경우를 말한다. 대각선상에 집이 있는 경우는 연결된 것이 아니다. <그림 2>는 <그림 1>을 단지별로 번호를 붙인 것이다. 지도를 입력하여 단지수를 출력하고, 각 단지에 속하는 집의 수를 오름차순으로 정렬하여 출력하는 프로그램을 작성하시오.
입력
첫 번째 줄에는 지도의 크기 N(정사각형이므로 가로와 세로의 크기는 같으며 5≤N≤25)이 입력되고, 그 다음 N줄에는 각각 N개의 자료(0혹은 1)가 입력된다.
출력
첫 번째 줄에는 총 단지수를 출력하시오. 그리고 각 단지내 집의 수를 오름차순으로 정렬하여 한 줄에 하나씩 출력하시오.
예제 입력
7 0110100 0110101 1110101 0000111 0100000 0111110 0111000
예제 출력
3 7 8 9
코드
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int n;
static int map[][];
static boolean visited[][];
static int count = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
map = new int[n][n];
visited = new boolean[n][n];
ArrayList<Integer> result = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
String str = sc.next();
for (int j = 0; j < n; j++)
map[i][j] = Integer.parseInt(str.substring(j, j + 1));
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (map[i][j] > 0 && !visited[i][j]) {
count = 0;
bfs(i, j);
result.add(count);
}
}
}
Collections.sort(result);
int size = result.size();
System.out.println(size);
for (int i = 0; i < size; i++)
System.out.println(result.get(i));
}
static void bfs(int a, int b) {
int dx[] = { 1, -1, 0, 0 };
int dy[] = { 0, 0, 1, -1 };
Queue<node> q = new LinkedList();
q.add(new node(a, b));
visited[a][b] = true;
count++;
while (!q.isEmpty()) {
node tmp = q.poll();
for (int i = 0; i < 4; i++) {
int x = tmp.a + dx[i];
int y = tmp.b + dy[i];
if (x > -1 && x < n && y > -1 && y < n && map[x][y] > 0) {
if (!visited[x][y]) {
count++;
visited[x][y] = true;
q.add(new node(x, y));
}
}
}
}
}
public static class node {
int a, b;
public node(int a, int b) {
this.a = a;
this.b = b;
}
}
}
'Algorithm > AlgorithmJobs' 카테고리의 다른 글
[AJ/BFS] 전염병 (0) | 2019.10.08 |
---|---|
[AJ/BFS] 이상한 계산기 (0) | 2019.10.07 |
[AJ/BFS] 미로찾기 (0) | 2019.10.07 |
[AJ/BFS] 웜 바이러스 (0) | 2019.10.03 |
[AJ/BFS] 이분 그래프 판별 (0) | 2019.10.03 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- hash
- 백 트래킹
- 사회망서비스
- programmers
- Objective function
- MFQ
- MLQ
- DFS
- 프로세스 스케줄링
- loss function
- 3-way-handshake
- 자료구조
- Android
- SRTN
- 기능개발
- 프로그래머스
- hashtable
- 알고리즘
- N-Queen
- 4-way-handshake
- git
- 우선순위큐
- 농협정보시스템IT
- SWExpert
- algorithm
- binarySearch
- Process Scheduling
- 네트워크
- 백트래킹
- java
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함