https://www.acmicpc.net/problem/2667
2667번: 단지번호붙이기
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집들의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. �
www.acmicpc.net
# 문제풀이
- bfs로 푸는 문제 이며, 단지 수를 저장할대 ArrayList를 통해 넣었다.
- Collections.sort로 정렬하는 것을 여기서 알게됨
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int[][] map;
static boolean[][] visited;
static int[] dy = { -1, 0, 1, 0 };
static int[] dx = { 0, 1, 0, -1 };
static int N, cnt, ans;
static Queue<Point> que;
static ArrayList<Integer> al;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
map = new int[N][N];
visited = new boolean[N][N];
que = new LinkedList<>();
cnt = 0;
ans = 0;
al = new ArrayList<>();
for (int i = 0; i < N; i++) {
String str = sc.next();
for (int j = 0; j < N; j++) {
map[i][j] = str.charAt(j) - '0';
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (map[i][j] == 1) {
bfs(i, j);
cnt++;
}
}
}
Collections.sort(al);
System.out.println(cnt);
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i));
}
}
private static void bfs(int y, int x) {
que.offer(new Point(y, x));
visited[y][x] = true;
while (!que.isEmpty()) {
Point p = que.poll();
ans++;
for (int k = 0; k < 4; k++) {
int ny = p.y + dy[k];
int nx = p.x + dx[k];
if (ischecked(ny, nx) && !visited[ny][nx] && map[ny][nx] == 1) {
visited[ny][nx] = true;
map[ny][nx] = 0;
que.offer(new Point(ny, nx));
}
}
}
al.add(ans);
ans = 0;
}
private static boolean ischecked(int my, int mx) {
if (my >= 0 && my < N && mx >= 0 && mx < N) {
return true;
}
return false;
}
static class Point {
int y;
int x;
public Point(int y, int x) {
super();
this.y = y;
this.x = x;
}
}
static void print() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(map[i][j]);
}
System.out.println();
}
System.out.println();
}
}
'JAVA 알고리즘 ' 카테고리의 다른 글
SWEA 2805번 - 농작물 수확하기 (1) | 2020.06.27 |
---|---|
SWEA 8104번 - 조 만들기 (0) | 2020.06.27 |
백준 1260번 - DFS와 BFS (2) | 2020.06.25 |
백준2573번 - 빙산 (1) | 2020.06.24 |
백준12761번 - 돌다리 (0) | 2020.06.24 |