728x90
반응형
import java.io.*;
import java.util.*;
class Point{
int x,y;
Point(int x,int y){
this.x = x;
this.y = y;
}
}
public class Main {
static int [][] board,check;
static int cnt;
static int[] dx = {1,0,-1,0};
static int[] dy = {0,1,0,-1};
static int n,m;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine()," ");
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
board = new int[n][m];
check = new int[n][m];
cnt = 0;
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine()," ");
for (int j = 0; j < m; j++) {
board[i][j] = Integer.parseInt(st.nextToken());
if(board[i][j]==1){
cnt++;
}
}
}
bfs();
}
private static void printMap(){
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print(board[i][j]+" ");
}
System.out.println();
}
System.out.println();
}
private static void bfs() {
Queue<Point> q = new LinkedList<>();
int day = 1;
while (true) {
q.offer(new Point(0,0));
// System.out.println(day + " 일차");
// printMap();
check = new int[n][m];
int deleteElement = 0;
while (!q.isEmpty()) {
Point poll = q.poll();
int x = poll.x;
int y = poll.y;
check[x][y] = 1;
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (0 <= nx && nx < n && 0 <= ny && ny < m) {
if (board[nx][ny] == 1 && check[nx][ny] == 0) {
board[nx][ny] = 2;
check[nx][ny] = 1;
deleteElement++;
}
if (board[nx][ny] == 0 && check[nx][ny] == 0) {
q.offer(new Point(nx, ny));
check[nx][ny] = 1;
}
}
}
}
//printMap();
if (deleteElement == cnt) {
System.out.println(day);
System.out.println(cnt);
return;
} else {
deleteOld();
cnt -= deleteElement;
day++;
}
//printMap();
}
}
private static void deleteOld() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if(board[i][j]==2){
board[i][j] = 0;
}
}
}
}
}
728x90
반응형
'알고리즘 > 해시' 카테고리의 다른 글
[백준] 1764번 듣보잡 #Java (0) | 2022.05.17 |
---|---|
[백준] 1620번 나는야 포켓몬 마스터 이다솜 #Java (0) | 2022.05.15 |
[알고리즘] 해쉬 총 정리 with Java (0) | 2022.03.17 |
[알고리즘] K번째 큰 수 with Java, set (0) | 2022.03.16 |
[알고리즘] 모든 아나그램 찾기 with Java (0) | 2022.03.16 |