티스토리 뷰

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

 

1697번: 숨바꼭질

수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일

www.acmicpc.net

const fs = require('fs');
const [N,K] = fs.readFileSync("./dev/stdin").toString().trim().split(" ").map(v=>+v);
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;
  }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; 
}
}

function check(n){
  return !isVisited[n]
}



let answer = 0;
let isVisited = new Array(100001).fill(false);


let q = new Queue();
q.push([N,0]);
isVisited[N] = true;

while(true){
  let [now,sec] = q.pop();
  if(now==K){
    answer = sec;
    break; 
  }else{
    if(now-1>=0 && check(now-1)){
      isVisited[now-1] = true; 
      q.push([now-1,sec+1])
    }
    if(now+1<100001 && check(now+1)){
      isVisited[now+1] = true; 
      q.push([now+1,sec+1])
    }
    if(now*2<100001 && check(now*2)){
      isVisited[now*2] = true; 
      q.push([now*2,sec+1])
    }
  }
}

console.log(answer)
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
글 보관함