import java.util.*;
public class Main {
public static boolean [][] vis = new boolean[502][502];
public static int [][] board = new int[502][502];
public static int n,m; // n > 행 m > 열
public static int [] dx = {1,0,-1,0};
public static int [] dy = {0,1,0,-1};
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
board[i][j] = sc.nextInt();
}
}
Queue<Pos> q = new LinkedList<>();
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
if(board[i][j] == 1 && vis[i][j] == false) {
vis[i][j] = true;
q.add(new Pos(i,j));
while(!q.isEmpty()) {
Pos cur = q.poll();// 큐에서 하나 뽑아냄
for(int dir = 0;dir<4;dir++) {
int nx = cur.x + dx[dir];
int ny = cur.y + dy[dir];
if(nx < 0 || nx >=n || ny < 0 || ny >= m) continue;
if(vis[nx][ny] || board[nx][ny] != 1) continue;
vis[nx][ny] = true;
q.add(new Pos(nx,ny));
}
}
}
}
}
}
}
class Pos{
int x;
int y;
Pos(int x,int y){
this.x = x;
this.y= y;
}
}
BFS 알고리즘 (너비 우선 탐색) - 배열 BFS, 그래프 BFS (2022-07-21 업데이트)
2022-07-21 업데이트 : 글 맨 아래에 '풀어보기'로 풀어볼만한 문제 링크 추가 BFS (Breadth-first Search) 명확히 검증하면서 쓴게 아니라서 틀린 부분 있으면 알려주세요! - BFS와 DFS 대충 곰처럼 생긴 섬이
nahwasa.com
https://github.com/encrypted-def/basic-algo-lecture/blob/master/0x09/BFS.cpp
GitHub - encrypted-def/basic-algo-lecture: 바킹독의 실전 알고리즘 강의 자료
바킹독의 실전 알고리즘 강의 자료. Contribute to encrypted-def/basic-algo-lecture development by creating an account on GitHub.
github.com
'Java > 실습' 카테고리의 다른 글
[Java] Segment Tree 구현 (0) | 2023.03.04 |
---|---|
[Java] 우선순위 큐 구현 (1) | 2023.01.29 |
[Java] deque (1) | 2022.07.26 |
[Java] 배열을 통한 queue(큐) 구현 (1) | 2022.07.25 |
[Java] 야매 연결리스트 구현 (0) | 2022.07.21 |