반응형
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static int nx []= {1,-1,0,0};
public static int ny []= {0,0,-1,1};
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int m=sc.nextInt();
int n=sc.nextInt();
int arr [][]=new int [m+2][n+2];
int arr2 [][]=new int [m+2][n+2];
boolean check [][]=new boolean[m+2][n+2];
for(int i=0;i<m+2;i++) {
Arrays.fill(arr[i],-1);
Arrays.fill(arr2[i],-1);
Arrays.fill(check[i], false);
}
for(int i=1;i<m+1;i++) {
for(int j=1;j<n+1;j++) {
arr[i][j]=sc.nextInt();
arr2[i][j]=arr[i][j];
}
}
//--- 여기까지 세팅 끝 ---
int day=0;
int flag=1;
while(flag==1) {
flag=0;
for(int i=1;i<m+1;i++) {
for(int j=1;j<n+1;j++) {
if(arr2[i][j]==1&&check[i][j]==false) {
check[i][j]=true;
flag=1;
for(int k=0;k<4;k++) {
//위아래옆이 0이면
if(arr2[i+nx[k]][j+ny[k]]==0) {
arr[i+nx[k]][j+ny[k]]=1;
check[i+nx[k]][j+ny[k]]=false;
}
}
}
}
}
if(flag==1) {
day++;
for(int i=0;i<m+2;i++) {
for(int j=0;j<n+2;j++) {
arr2[i][j]= arr[i][j];
}
}
}
}
boolean ans=true;
for(int i=0;i<m+2;i++) {
for(int j=0;j<n+2;j++) {
if(arr2[i][j]==0) ans=false;
}
}
if(ans==true) System.out.println(day);
else System.out.println(-1);
}
}
처음엔 배열 두개로 풀었는데
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static int nx []= {1,-1,0,0};
public static int ny []= {0,0,-1,1};
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int m=sc.nextInt();
int n=sc.nextInt();
int[][] arr = new int[m][n];
int cnt = 0;
int day = 0;
Queue<int[]> q = new LinkedList<>();
for(int j=0;j<n;j++) {
for(int i=0;i<m;i++) {
arr[i][j]=sc.nextInt();
if(arr[i][j]==1) {
q.add(new int [] {i,j});
}
else if(arr[i][j]==0)
cnt++;
}
}
//---세팅 끝---
//cnt는 토마토 갯수만큼 있음. 토마토 익힐 때마다 cnt--하고, cnt가 0이되면 탈출
while(!q.isEmpty()&&cnt>0) {
for (int s = q.size(); s > 0; s--) {
int temp []=q.poll();
for(int k=0;k<4;k++) {
int x=temp[0]+nx[k];
int y=temp[1]+ny[k];
//인덱스 범위 넘지 않도록
if(x>=0&&y>=00&&x<m&&y<n) {
if(arr[x][y]==0) {
arr[x][y]=1;
cnt--;
q.add(new int [] {x,y});
}
else {
continue;
}
}
}
}
day++;
}
//답 출력
if(cnt==0)
System.out.println(day);
else
System.out.println(-1);
}
}
큐를 이용한 bfs 풀이가 맞는것같아서 다시풀었다
반응형
'개발 관련 공부 > 알고리즘' 카테고리의 다른 글
백준 1697 숨바꼭질 (0) | 2021.08.25 |
---|---|
백준 7569 토마토2 (0) | 2021.08.24 |
백준 1302 베스트셀러 (0) | 2021.08.20 |
백준 9012 괄호 (0) | 2021.08.19 |
백준 10816 숫자카드2 (0) | 2021.08.18 |
댓글