https://www.acmicpc.net/problem/2667
ํ์ด
- ์ด์ ์ ํ์๋ ์์ญ๊ตฌํ๊ธฐ์ ์ ์ฌํ ๋ฌธ์ ๋ค. (https://marginata.tistory.com/173)
- ์์ญ๊ตฌํ๊ธฐ๊ฐ ์์น ๋์ง ์์ ์์ญ์ ๋์ด๋ฅผ ๊ตฌํ๊ฒ์ด๋ผ๋ฉด ๋ฐ๋๋ก ๋จ์ง๋ฒํธ๋ถ์ด๊ธฐ๋ ์ง์ด ์๋๊ณณ์ ๋์ด๋ฅผ ๊ตฌํ๋ฉด ๋๋ค.
- ์ฃผ์ํ ์ ์ 0001010 ์ด๋ฐ์์ผ๋ก ๊ณต๋ฐฑ์์ด ์ ๋ ฅ์ ๋ฐ๊ธฐ ๋๋ฌธ์ charAt()์ ์ด์ฉํด์ ํ์๋ฆฌ์ฉ charํ์ผ๋ก ์ถ์ถํ ๋ค์ ์ ์ํ์ผ๋ก ๋ณํํด์ค์ผ ํ๋ค.
์ ์ฒด ์ฝ๋
import java.io.*;
import java.util.*;
public class Main{
static int[][] map; //์ง๋
static int[] dx = {1,-1,0,0};
static int[] dy = {0,0,1,-1};
static int N; //์ง๋ ํฌ๊ธฐ
static int cnt; //์ง์ ์
static ArrayList<Integer> list = new ArrayList<>(); //์ง์ ์ ๊ฒฐ๊ณผ ์ ์ฅ
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
//map ํฌ๊ธฐ
map = new int[N][N];
//map ์ด๊ธฐํ
for(int i=0; i<N; i++){
String str = br.readLine();
for(int j=0; j<N; j++){
map[i][j] = str.charAt(j) - '0';
}
}
//DFS ํ์
for(int x=0; x<N; x++){
for(int y=0; y<N; y++){
if(map[x][y]==1){
cnt=0;
dfs(x,y);
list.add(cnt);
}
}
}
//์ถ๋ ฅ
System.out.println(list.size());
Collections.sort(list);
for(Integer n : list){
System.out.println(n);
}
}
//DFS ํ์
private static void dfs(int x, int y){
map[x][y]=0; //์ง์ด ์์ผ๋ฉด
cnt++;
for(int i=0; i<4; i++){
int nx = x+dx[i];
int ny = y+dy[i];
if(nx>=0 && nx<N && ny>=0 && ny<N){
if(map[nx][ny]==1){ //์ง์ด ์์ผ๋ฉด ํ์ ๊ณ์
dfs(nx, ny);
}
}
}
}
}
'Algorithm > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Silver III/JAVA] 16956 ๋๋์ ์ (0) | 2024.12.25 |
---|---|
[Silver I/JAVA] 3187 ์์น๊ธฐ ๊ฟ (0) | 2024.12.19 |
[Silver I/JAVA] 2583 ์์ญ ๊ตฌํ๊ธฐ (0) | 2024.12.12 |
[Silver II/JAVA] 2210 ์ซ์ํ ์ ํ (0) | 2024.12.12 |
[Silver IV/JAVA] 1388 ๋ฐ๋ฅ์ฅ์ (2) | 2024.12.10 |