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
๊ด€๋ฆฌ ๋ฉ”๋‰ด

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

Q4963 ์„ฌ์˜ ๊ฐœ์ˆ˜ JAVA ๋ณธ๋ฌธ

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

Q4963 ์„ฌ์˜ ๊ฐœ์ˆ˜ JAVA

JihyunLee 2019. 5. 7. 15:56
๋ฐ˜์‘ํ˜•
package graph;
import java.util.*;
public class Q4963 {
//์„ฌ์˜ ๊ฐฏ์ˆ˜๋ฅผ ์„ธ๋Š” ๋ฌธ์ œ 
	static int[] di = {-1,0,1,-1,1,-1,0,1};
	static int[] dj = {-1,-1,-1,0,0,1,1,1};
	static int arr[][];
	static int visit[][];
	static int w,h;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int cnt=0;
		Scanner scan = new Scanner(System.in);
		StringTokenizer st;
		
		while(true) {
			cnt=0;
			String s = scan.nextLine();
			st = new StringTokenizer(s," ");
			w = Integer.parseInt(st.nextToken());
			h = Integer.parseInt(st.nextToken());
			if(w==0 && h==0)	break;
			arr = new int[h][w];
			visit = new int[h][w];
			for(int i=0; i<h; i++) {
				s = scan.nextLine();
				st = new StringTokenizer(s," ");
				for(int j=0; j<w; j++) {
					arr[i][j] = Integer.parseInt(st.nextToken());
				}
			}
			//์ž…๋ ฅ์™„๋ฃŒ
			for(int i=0; i<h; i++) {
				for (int j=0; j<w; j++) {
					if(arr[i][j]==1 && visit[i][j]==0) {
						find(i,j);
						cnt++;
					}
						
					
				}
			}
			System.out.println(cnt);
			
		}

	}
	public static void find(int i, int j) {
		visit[i][j] = 1;
		for(int k=0; k<8; k++) {
			int ni = i + di[k];
			int nj = j + dj[k];
			if(ni>=0 && nj>=0 && ni<h && nj<w) {
				if(arr[ni][nj]==1 && visit[ni][nj]==0) {
					find(ni,nj);
				}
			}
		}
	}

}
๋ฐ˜์‘ํ˜•