티스토리 뷰

https://www.acmicpc.net/problem/7569

 

7569번: 토마토

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N과 쌓아올려지는 상자의 수를 나타내는 H가 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M ≤ 100, 2 ≤ N ≤ 100,

www.acmicpc.net

const fs = require('fs');
const [table, ...arr] = fs.readFileSync("./dev/stdin").toString().trim().split("\n");
const [C,R,H] = table.split(' ').map(v=>+v);
const tomatoes = arr.map(v=>v.split(' ').map(w=>+w));
const tomato = [];

class Node{
  constructor(item){
    this.item = item;
    this.next = null;
  }
}

class Queue{
  constructor(){
    this.head = null;
    this.tail = null;
    this.length = 0;
  }

  push(item){
    const node = new Node(item)
    if(this.head==null){
      this.head= node;
      this.head.next = null;
    }else{
      this.tail.next = node;
    }

    this.tail = node;
    this.length +=1;
  }

  pop(){
    const popItem = this.head;
    this.head = this.head.next;
    this.length -=1;
    return popItem.item;
  }

  size(){
    return this.length;
  }

  empty(){
    if(this.length==0){
      return 1;
    }else{
      return 0;
    }
  }

  front(){
    if(this.empty()==1) return -1;
    return this.head.item; 
  }

  back(){
    if(this.empty()==1) return -1;
    return this.tail.item; 
  }
}

for(let i = 0; i<H; i++){
  let temp = [];
  for(let j = i*R; j<(i+1)*R;j++){
    temp.push([-1,...tomatoes[j],-1]);
  }
  temp.unshift(new Array(C+2).fill(-1));
  temp.push(new Array(C+2).fill(-1));
  tomato.push(temp);
}

tomato.unshift(Array.from(Array(R+2), () => Array(C+2).fill(-1)));
tomato.push(Array.from(Array(R+2), () => Array(C+2).fill(-1)));

let q = new Queue();
let unripe = 0;
let days = 0; 


for(let h = 1; h<tomato.length-1; h++){
  for(let r = 1; r<tomato[0].length-1; r++){
    for(let c = 1; c<tomato[0][0].length-1; c++){
      // console.log(h,r,c ,tomato[h][r][c])
      if(tomato[h][r][c]==1){
        q.push([h,r,c,1]);
      }
      if(tomato[h][r][c]==0){
        unripe++; 
      }
    }
  }
}

while(q.length>0){
  let [h,r,c,n] = q.pop();
  if(n>days) days = n;

  if(tomato[h-1][r][c]==0){
    tomato[h-1][r][c]=1;
    q.push([h-1,r,c,n+1])
    unripe--;
  }

  if(tomato[h+1][r][c]==0){
    tomato[h+1][r][c]=1;
    q.push([h+1,r,c,n+1])
    unripe--;
  }

  if(tomato[h][r-1][c]==0){
    tomato[h][r-1][c]=1;
    q.push([h,r-1,c,n+1])
    unripe--;
  }

  if(tomato[h][r+1][c]==0){
    tomato[h][r+1][c]=1;
    q.push([h,r+1,c,n+1])
    unripe--;
  }

  if(tomato[h][r][c-1]==0){
    tomato[h][r][c-1]=1;
    q.push([h,r,c-1,n+1])
    unripe--;
  }
  if(tomato[h][r][c+1]==0){
    tomato[h][r][c+1]=1;
    q.push([h,r,c+1,n+1])
    unripe--;
  }
  
}


if(unripe!=0){
  console.log(-1);
}else{
  console.log(days-1)
}
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함