Dev.baelanche

[백준 7569] 토마토 본문

Data Structure & Algorithm/PS - JAVA

[백준 7569] 토마토

baelanche 2019. 6. 8. 15:38
반응형

 

 

상, 하, 좌, 우, 위, 아래로 퍼진다는 것만 유의하며 BFS 를 하면 된다.

 

int dh[] = {0, 0, 0, 0, -1, 1}; //위, 아래
int dn[] = {-1, 1, 0, 0, 0, 0}; //상, 하
int dm[] = {0, 0, -1, 1, 0, 0}; //좌, 우

 

나는 이렇게 해결했다.

 

 

처음부터 모두 익어있다면 0, 모두 익지 못한다면 -1이 출력되는 부분을 따로 예외처리 해주었다.

 

int cnt = -1; //기본 카운트

while(!q.isEmpty()) {
	//로직 수행
    
    cnt++;
}

for() {
	//토마토 배열 체크
}

//딱 한번 수행되고 멈추었다면 안익은 토마토가 없다는 뜻이므로 0 출력
//토마토 배열을 체크하여 안익은 토마토가 있다면 -1 출력
//모두 익었다면 cnt 출력

 

간단히 써보았는데 잘썼는지 모르겠다.

 

 

 

전체 소스

 

public class Main {
    
    static int m;
    static int n;
    static int h;
    static int a[][][];
    static Queue<Pair> q = new LinkedList<Pair>();
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        m = sc.nextInt();
        n = sc.nextInt();
        h = sc.nextInt();
        
        a = new int[h][n][m];
        
        for(int i=0; i<h; i++)
            for(int j=0; j<n; j++)
                for(int k=0; k<m; k++) {
                    a[i][j][k] = sc.nextInt();
                    if(a[i][j][k] == 1) q.offer(new Pair(i, j, k));
                }
        
        System.out.println(bfs());
    }
    
    public static int bfs() {
        int cnt = -1;
        
        while(!q.isEmpty()) {
            int size = q.size();
            
            while(size-->0) {
                int dh[] = {0, 0, 0, 0, -1, 1};
                int dn[] = {-1, 1, 0, 0, 0, 0};
                int dm[] = {0, 0, -1, 1, 0, 0};
                
                Pair p = q.poll();
                int mh = p.h;
                int mn = p.n;
                int mm = p.m;
                for(int i=0; i<6; i++) {
                    int nh = mh + dh[i];
                    int nn = mn + dn[i];
                    int nm = mm + dm[i];
                    if(0 <= nh && nh < h && 0 <= nn && nn < n && 0 <= nm && nm < m) {
                        if(a[nh][nn][nm] == 0) {
                            q.offer(new Pair(nh, nn, nm));
                            a[nh][nn][nm] = 1;
                        }
                    }
                }
            }
            cnt++;
        }
        
        for(int i=0; i<h; i++)
            for(int j=0; j<n; j++)
                for(int k=0; k<m; k++)
                    if(a[i][j][k] == 0)
                        return -1;
        
        return cnt;
    }
    
    static class Pair {
        int h;
        int n;
        int m;
        
        Pair(int h, int n, int m) {
            this.h = h;
            this.n = n;
            this.m = m;
        }
    }
}
반응형

'Data Structure & Algorithm > PS - JAVA' 카테고리의 다른 글

[백준 10451] 순열 사이클  (0) 2019.06.08
[백준 1890] 점프  (0) 2019.06.08
[백준 2108] 통계학  (0) 2019.06.08
[백준 9020] 골드바흐의 추측  (0) 2019.06.08
[백준 1080] 행렬  (0) 2019.06.04
Comments