일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- DFS
- 데이터베이스
- join
- BFS
- java
- IntelliJ
- Greedy
- select
- 프로그래머스
- 백준
- SQL
- 깊이우선탐색
- Effective Java
- mariaDB
- 정렬
- springboot
- 그리디알고리즘
- 다이나믹프로그래밍
- db
- mybatis
- 피보나치
- 알고리즘
- 코테
- 너비우선탐색
- Spring
- 우선순위큐
- Database
- 탐욕법
- DP
- 이펙티브자바
Archives
- Today
- Total
땀두 블로그
[백준] 2667번 - 단지번호 붙이기 본문


BFS를 이용한 문제이다. 각각의 덩어리를 만들기 위해서 2중 for문을 이용해주고, 상하좌우를 탐색하며 인근 노드들을 탐색하여 해결할 수 있다.
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;
class node2667 {
int x;
int y;
node2667(int x, int y) {
this.x = x;
this.y = y;
}
}
public class p2667 {
public static int[] nx = { -1, 0, 0, 1 };
public static int[] ny = { 0, 1, -1, 0 };
public static int[][] ary;
public static int a;
public static boolean[][] visited;
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
a = Integer.parseInt(br.readLine());
ary = new int[a][a];
visited = new boolean[a][a];
for (int i = 0; i < a; i++) {
String[] s = br.readLine().split("");
for (int j = 0; j < a; j++) {
ary[i][j] = Integer.parseInt(s[j]);
}
}
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < a; i++) {
for (int j = 0; j < a; j++) {
if (visited[i][j] == false && ary[i][j] == 1) {
list.add(bfs(i, j));
}
}
}
System.out.println(list.size());
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
public static int bfs(int row, int col) {
int count = 1;
Queue<node2667> q = new LinkedList<>();
q.add(new node2667(row, col));
visited[row][col] = true;
while (!q.isEmpty()) {
node2667 n = q.poll();
for (int i = 0; i < 4; i++) {
int x = n.x + nx[i];
int y = n.y + ny[i];
if (x >= 0 && y >= 0 && x < a && y < a) {
if (ary[x][y] == 1 && visited[x][y] == false) {
q.add(new node2667(x, y));
visited[x][y] = true;
count++;
}
}
}
}
return count;
}
}
'알고리즘 > 백준' 카테고리의 다른 글
[백준] 1235번 - 학생 번호 (0) | 2022.03.22 |
---|---|
[백준] 1120번 - 문자열 (0) | 2022.03.22 |
[백준] 1389번 - 케빈 베이컨의 6단계 법칙 (0) | 2022.03.22 |
[백준] 11022번 - A+B-8 (0) | 2022.03.22 |
[백준] 11021번 - A+B-7 (0) | 2022.03.22 |
Comments