본문 바로가기

전공지식/알고리즘

[백준][그래프][2667] 단지번호붙이기

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

class Pair{
	int x;
	int y;
	
	Pair(int x, int y){
		this.x = x;
		this.y = y;
	}
}
public class Graph {

	public static final int[] dx = {0, 0, 1, -1};
	public static final int[] dy = {1, -1, 0, 0};
	
	static void bfs(int[][] arr, int[][] group, int x, int y, int n, int cnt){
		Queue queue = new LinkedList();
		queue.add(new Pair(x, y));
		group[x][y] = cnt;
		
		Pair temp = null;
		while(!queue.isEmpty()){
			temp = queue.remove();
			
			for(int i=0; i<4; i++){
				int nx = temp.x + dx[i];
				int ny = temp.y + dy[i];
				if(nx >= 0 && nx < n && ny >= 0 && ny < n){
					if(group[nx][ny] == 0 && arr[nx][ny] == 1){
						queue.add(new Pair(nx, ny));
						group[nx][ny] = cnt;
					}
				}
			}
			
		}
	}
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		int n = sc.nextInt();
		sc.nextLine();
		
		int[][] a = new int[n][n];
		int[][] group = new int[n][n];
		String input = "";
		
		for(int i=0; i<n; i++){
			input = sc.nextLine();
			for(int j=0; j<n; j++){
				a[i][j] = input.charAt(j) - '0';
			}
		}
		
		int cnt = 0;
		for(int i=0; i<n; i++){
			for(int j=0; j<n; j++){
				if(a[i][j] == 1 && group[i][j] == 0){
					bfs(a, group, i, j, n, ++cnt);
				}
			}
		}
		
		int[] ans = new int[cnt];
		
		for(int i=0; i<n; i++){
			for(int j=0; j<n; j++){
				if(group[i][j] != 0){
					ans[group[i][j] - 1] += 1;
				}
			}
		}
		
		System.out.println(cnt);

		for(int i=0; i<cnt; i++){
			System.out.println(ans[i]);
		}
	}
}

'전공지식 > 알고리즘' 카테고리의 다른 글

[백준][11729] 하노이탑 이동 문제  (0) 2017.01.22
[알고리즘]Scanner vs BufferReader  (1) 2017.01.22
[백준][DP][9465]스티커  (0) 2016.12.18
[백준][DP][2011] 암호코드  (2) 2016.12.17
[백준][DP][2193] 이친수  (0) 2016.12.15