본문 바로가기

코딩테스트(백준)

[백준] 4963 : 섬의 개수 -JAVA - 사좋배 공유

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

public class Main {

	static int[][] arr;
	static int dx[]= {-1,-1,0,1,1,1,0,-1};
	static int dy[]= {0,1,1,1,0,-1,-1,-1};
	static int w,h;
	static int count;
	static Queue q;
	static int result;
	static boolean [][]visit;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while(true) {
			w = sc.nextInt();
			h = sc.nextInt();
			arr=new int[h][w];
			visit=new boolean[h][w];
			count=0;
			q= new LinkedList();
			if(w==0&&h==0) {
				return;
			}
			for(int i=0;i<h;i++) {
				for(int j=0;j<w;j++) {
					arr[i][j]=sc.nextInt();
				}
			}
			result=0;
			for(int i=0;i<h;i++) {
				for(int j=0;j<w;j++) {
					if(arr[i][j]==1) {
						result++;
						DFS(i,j);
					}
				}
			}
			System.out.println(result);
		}
	}
	private static void DFS(int x,int y) {

		//실행
		for(int i=0;i<8;i++) {
			int rx = x+dx[i];
			int ry = y+dy[i];
			if(rx<0||ry<0||rx>=h||ry>=w||arr[rx][ry]==0) {
				continue;
			}if(visit[rx][ry]==true) {
				continue;
			}
			visit[rx][ry]=true;
			arr[rx][ry]=0;
			DFS(rx,ry);
		}
	}	
}
class data{
	int x;
	int y;
	int count;
	data(int x, int y,int count){
		this.x=x;
		this.y= y;
		this.count= count;
	}
}