풀이에 Pointer 클래스를 사용한 것 이외에는 거의 비슷하다
import java.util.*;
class Pointer{
int x; int y;
Pointer(int x, int y){
this.x = x;
this.y = y;
}
}
class Main{
static int[] dx = {-1,0,1,0,-1,-1,1,1};
static int[] dy = {0,1,0,-1,-1,1,1,-1};
static int[][] board;
static Queue<Pointer> Q = new LinkedList<>();
static int res = 0, n;
public void Solution(){
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
if (board[i][j] == 1){
board[i][j] = 0;
res++;
BFS(i, j);
}
}
}
}
public void BFS(int i, int j){
Q.add(new Pointer(i, j));
while (!Q.isEmpty()){
Pointer tmp = Q.poll();
for (int k = 0; k < 8; k++){
int nx = tmp.x+ dx[k];
int ny = tmp.y + dy[k];
if (nx >= 0 && nx < n && ny >= 0 && ny < n && board[nx][ny] == 1){
board[nx][ny] = 0;
Q.add(new Pointer(nx, ny));
}
}
}
}
public static void main(String[] args) {
Main T = new Main();
Scanner in = new Scanner(System.in);
n = in.nextInt();
board = new int[n][n];
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
board[i][j] = in.nextInt();
}
}
T.Solution();
System.out.println(res);
}
}
'알고리즘 이전 > 재귀, DFS, BFS, Tree, Graph' 카테고리의 다른 글
피자 배달 거리 (0) | 2023.09.03 |
---|---|
섬나라 아일랜드(DFS) (0) | 2023.09.03 |
토마토(BFS 활용) (0) | 2023.09.01 |
미로의 최단거리(BFS) (0) | 2023.08.31 |
DFS 미로찾기 (0) | 2023.08.31 |