Notice
Recent Posts
Recent Comments
ยซ   2024/11   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
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
Tags more
Archives
Today
Total
๊ด€๋ฆฌ ๋ฉ”๋‰ด

๐ŸŒฒ์ž๋ผ๋‚˜๋Š”์ฒญ๋…„

Q 2667 ๋‹จ์ง€๋ฒˆํ˜ธ ๋ถ™์ด๊ธฐ JAVA ๋ณธ๋ฌธ

์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œํ’€์ด

Q 2667 ๋‹จ์ง€๋ฒˆํ˜ธ ๋ถ™์ด๊ธฐ JAVA

JihyunLee 2019. 5. 7. 11:22
๋ฐ˜์‘ํ˜•

dfs ๋ฅผ ์–ด๋–ป๊ฒŒ ์“ฐ๋Š”๊ฑด๊ฐ€ ๊ณ ๋ฏผํ–ˆ์—ˆ๋Š”๋ฐ ๊ตฌ๊ธ€๋ง์„ ํ•˜๋‹ค๋ณด๋‹ˆ dfs๋ฅผ ์•„๋ž˜ ์œ„ ์–‘ ์˜† ์ด๋ ‡๊ฒŒ ๋„ค ๋ฐฉํ–ฅ์œผ๋กœ ์‚ฌ์šฉํ•˜๋Š” ๋ฌธ์ œ์ธ ๊ฒƒ์„ ์•Œ๊ฒŒ ๋˜์—ˆ๋‹ค.

package graph;
import java.util.*;

public class Q2667 {
	static int[][]arr;
	static int[][]visit;
	static int[] di = {-1,0,1,0};
	static int[] dj = {0 ,-1,0,1};
	static int num, cnt;
	public static void main(String[] args) {
		Scanner scan =new Scanner(System.in);
		num = Integer.parseInt(scan.nextLine());
		arr = new int[num][num];
		visit = new int[num][num];
		ArrayList cnts = new ArrayList<Integer>();
		
		
		for(int i=0; i<num; i++) {
			String s = new String();
			s= scan.nextLine();
			for(int j=0; j<num; j++) {
				if(s.charAt(j)=='0')
					arr[i][j]=0;
				else
					arr[i][j]=1;
			}
		}
		
		for(int i=0; i<num; i++) {
			for(int j=0; j<num; j++) {
				if(arr[i][j]==1 && visit[i][j]==0) {
					cnt=0;
					find(i,j);
					cnts.add(cnt);
				}
			}
		}
		Collections.sort(cnts);
		System.out.println(cnts.size());
		for(int i=0; i<cnts.size(); i++) {
			System.out.println(cnts.get(i));
		}
		

	}
	//๋ฐฉ๋ฌธํ–ˆ๋‹ค๋ฉด find =1
	public static void find(int i, int j) {
		
		visit[i][j]=1;
		cnt++;
		for(int k=0; k<4; k++) {
			int ni = i + di[k];
			int nj = j + dj[k];
			
			if(ni>=0 && nj>=0 && ni<num && nj<num && arr[ni][nj]==1 && visit[ni][nj]==0) {
				find(ni, nj);
			}
		}
		
		
		
	}
	
	
	
}
๋ฐ˜์‘ํ˜•