๐ [๋ฐฑ์ค์๊ณ ๋ฆฌ์ฆ ํ์ด] Q.2667 ๋จ์ง๋ฒํธ ๋ถ์ด๊ธฐ
๐ ๋ฌธ์
https://www.acmicpc.net/problem/2667
๐ ์ ๊ทผ๋ฒ
๋จ์ง๋ฒํธ ๋ถ์ด๊ธฐ ๋ฌธ์ ์ ๋๋ค.
๋ช๊ฐ์ ๋จ์ง๊ฐ ์๊ณ ํด๋น ๋จ์ง๋ง๋ค ์ด ๋ช๊ฐ๊ตฌ๊ฐ ์๋์ง๋ฅผ ๊ตฌํด์ผ ํฉ๋๋ค.
bfs ํ์์ ์ด์ฉํด์ ํ์ด๊ฐ ๊ฐ๋ฅํฉ๋๋ค.
์ (0,-1)
ํ (0,1)
์ข (-1,0)
์ฐ (1,0) ์ ํ ์ข ์ฐ ํ์นธ์ฉ์ ํ์ํ๋ฉฐ
์์ง ๋ฐฉ๋ฌธํ์ง ์์ ๊ณณ์ด๋ผ๋ฉด
๋ฐฉ๋ฌธ์ ํ๋ฉฐ bfs๋ฅผ ๋ฐ๋ณตํฉ๋๋ค.
๋ฐฉ๋ฌธํ์ง ์์ ์๋ก์ด ๋จ์ง์ ์ฒซ ์ง๋ถํฐ ๋ฐฉ๋ฌธํด
ํด๋น ๋จ์ง์ ๋ฐฉ๋ฌธํ ๊ฐ๊ตฌ ์๋ฅผ houseCount ๋ฆฌ์คํธ์ ์ ์ฅํฉ๋๋ค.
houseCount ๋ฆฌ์คํธ์ ๊ธธ์ด๊ฐ
๋จ์ง์ ์๊ฐ ๋๋ฉฐ houseCount์ ๋ฆฌ์คํธ์
๊ฐ๋ค์ด ๋จ์ง์ ๊ฐ๊ตฌ ์๊ฐ ๋ฉ๋๋ค.
houseCount ์ ๊ธธ์ด์
houseCount ๋ฆฌ์คํธ๋ฅผ ์ ๋ ฌ์ ํด์ ์ถ๋ ฅํด์ฃผ๋ฉด ๋์ ๋๋.
๐ป ์ฝ๋
package problem.bfs.Q2667;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
public class Main_2667 {
public static int n;
public static boolean [][] visited;
public static int [][] house;
public static int moveX[] = {0,0,-1,1};
public static int moveY[] = {-1,1,0,0};
public static ArrayList<Integer> houseCount = new ArrayList<>();
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
input();
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(house[i][j] == 1 && !visited[i][j]){
bfs(i,j);
}
}
}
Collections.sort(houseCount);
bw.write(Integer.toString(houseCount.size())+"\n");
for(int i=0; i<houseCount.size(); i++){
bw.write(Integer.toString(houseCount.get(i))+"\n");
}
bw.flush();
bw.close();
}
public static void input() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
visited = new boolean[n][n];
house = new int[n][n];
for(int i=0; i<n; i++){
String temp[] = br.readLine().split("");
for(int j=0; j<n; j++){
house[i][j] = Integer.parseInt(temp[j]);
}
}
br.close();
}
public static void bfs (int a, int b) {
Queue<int[]> queue = new LinkedList();
queue.offer(new int[]{a, b});
visited[a][b] = true;
int count = 1;
while (!queue.isEmpty()){
int coordinate[] = queue.poll();
for(int i=0; i<4; i++){
int x = coordinate[0] + moveX[i];
int y = coordinate[1] + moveY[i];
if ( x < 0 || y< 0 || x>=n || y>=n)
continue;
if ( house[x][y] == 0 || visited[x][y] == true)
continue;
queue.offer(new int[]{x,y});
visited[x][y] = true;
count++;
}
}
houseCount.add(count);
}
}
Written on June 12, 2020