Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- 백준 4375
- java 올림
- 백준 17425
- Algorithm
- 프로그래머스 네트워크 java
- java 반올림
- 프로그래머스 연속된 수의 합 java
- Codility
- mysql
- 0으로 채우기
- 백준 16927
- 알고리즘
- time complexity
- 프로그래머스 옹알이 java
- 백준 16935
- 프로그래머스 도둑질 java
- sort
- 자바
- 백준 18290
- 백준 14391
- 코딩테스트
- 프로그래머스 숫자의 표현 java
- Math.ceil()
- java 내림
- 백준 15661
- java
- 백준 11723
- Arrays
- 네트워크
- Math.floor()
Archives
- Today
- Total
취미처럼
[백준] 2667번 단지번호붙이기 본문
https://www.acmicpc.net/problem/2667
2667번: 단지번호붙이기
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여
www.acmicpc.net
import java.util.*;
import java.io.*;
public class Main {
// 정사각형 크기
static int N;
// 아파트
static int[][] map;
// 방문여부
static boolean[][] visit;
// 방향
static int[] dy = { 0, 1, 0, -1 };
static int[] dx = { 1, 0, -1, 0 };
// 단지번호
static int number;
// 단지별 집 카운트
static int count;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
List<Integer> list = new ArrayList<>();
N = Integer.parseInt(br.readLine());
map = new int[N][N];
visit = new boolean[N][N];
for (int i = 0; i < N; i++) {
String input = br.readLine();
for (int j = 0; j < N; j++) {
map[i][j] = input.charAt(j) - '0';
}
}
// 1이 집이 있는 곳
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (!visit[i][j] && map[i][j] == 1) {
// 단지별 집카운트 초기화
count = 0;
// 단지 번호 카운트
number++;
dfs(i, j);
list.add(count);
}
}
}
Collections.sort(list);
StringBuilder sb = new StringBuilder();
sb.append(number).append("\n");
for(int c : list) {
sb.append(c).append("\n");
}
System.out.print(sb);
}
public static void dfs(int y, int x) {
visit[y][x] = true;
// 맵에 단지 번호 부여
map[y][x] = number;
// 단지별 집 카운트
count++;
for(int i = 0; i < 4; i++) {
int ny = dy[i] + y;
int nx = dx[i] + x;
// 범위 체크
if(ny >= 0 && ny < N && nx >= 0 && nx < N) {
if(!visit[ny][nx] && map[ny][nx] == 1) {
dfs(ny, nx);
}
}
}
}
}
'Algorithm > 백준' 카테고리의 다른 글
[백준] 7576번 토마토 (0) | 2021.03.11 |
---|---|
[백준] 2178번 미로 탐색 (0) | 2021.03.11 |
[백준] 1707번 이분 그래프 (0) | 2021.03.11 |
[백준] 11724번 연결 요소의 개수 (0) | 2021.03.11 |
[백준] 1260번 DFS와 BFS (0) | 2021.03.09 |
Comments