https://www.acmicpc.net/problem/4963
나의풀이
import java.util.*;
import java.io.*;
public class Main {
static int[] dx = {-1,1,0,0,1,1,-1,-1};//대각선으로도 갈 수 있다는걸 고려
static int[] dy = {0,0,1,-1,-1,1,-1,1};
public static class Node{
int x,y;
public Node(int x, int y){
this.x=x;
this.y=y;
}
}
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
int answer=0;
int w=1, h=1;
while(true){
st = new StringTokenizer(br.readLine());
w= Integer.parseInt(st.nextToken());//너비
h= Integer.parseInt(st.nextToken());//높이
if( w==0 && h==0){
break;
}
int[][] map = new int[h][w];
for(int i=0; i<h; i++){
st = new StringTokenizer(br.readLine());
for(int j=0; j<w; j++){
int temp = Integer.parseInt(st.nextToken());
map[i][j]=temp;
}
}
boolean[][] visited=new boolean[h][w];
for(int i=0; i<h; i++){
for(int j=0; j<w; j++){
if(visited[i][j] == false && map[i][j] == 1){
Queue<Node> q = new LinkedList<>();
Node now = new Node(i,j);
q.offer(now);
visited[i][j]=true;
while(!q.isEmpty()){
now=q.poll();
for(int k=0; k<8; k++){
int nextX=now.x+dx[k];
int nextY=now.y+dy[k];
if(nextX<0 || nextY<0 || nextX>= h || nextY >= w){
continue;
}
if(visited[nextX][nextY] == true || map[nextX][nextY] == 0){
continue;
}
q.offer(new Node(nextX, nextY));
visited[nextX][nextY]= true;
}
}
answer++;
}
}
}
bw.write(Integer.toString(answer)+"\n");
answer=0;
}
bw.flush();
br.close();
bw.close();
}
}
'코테풀이' 카테고리의 다른 글
[프로그래머스] 공원 산책 java 풀이 (level1) (0) | 2023.04.20 |
---|---|
[백준] BOJ - 2644 촌수계산 java (실버2) (0) | 2023.04.12 |
[백준] BOJ - 11724 연결 요소의 개수 java(실버2) (0) | 2023.04.12 |
[백준] BOJ - 2075 N번째 큰 수 java (실버2) (0) | 2023.04.06 |
[백준] BOJ - 2304 창고 다각형 java (실버2) (0) | 2023.04.04 |