티스토리 뷰

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

 

7562번: 나이트의 이동

체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수

www.acmicpc.net

const fs = require('fs');
const [n, ...arr] = fs.readFileSync("./dev/stdin").toString().trim().split("\n");

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; 
  }
}


function check(r,c){
  return !isVisited[r][c]
}


const N = +n;
const knight = arr.map(v=>v.split(' ').map(w=>+w));
let answer = [];


for(let i  = 0; i<N; i++){
  const square = knight.shift()[0];
  const start  = knight.shift();
  const isVisited = Array.from(Array(square), () => Array(square).fill(false))
  const end = knight.shift();
  function check(r,c){
    return !isVisited[r][c];
  }
  

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

while(true){
  const [y,x,c] = q.pop();
  if(y==end[0] && x==end[1]){
    answer.push(c)
    break;
  }else{
    if(y+2<square && x+1<square &&check(y+2,x+1)){
      isVisited[y+2][x+1] = true;
      q.push([y+2,x+1,c+1])
    }
    if(y+2<square && x-1>-1 && check(y+2,x-1)){
      isVisited[y+2][x-1] = true;
      q.push([y+2,x-1,c+1])
    }
    if(y-2>-1 && x-1>-1 && check(y-2,x-1)){
      isVisited[y-2][x-1] = true;
      q.push([y-2,x-1,c+1])
    }
    if(y-2>-1 && x+1<square&& check(y-2,x+1)){
      isVisited[y-2][x+1] = true;
      q.push([y-2,x+1,c+1])
    }
    if(y+1<square && x+2<square&& check(y+1,x+2)){
      isVisited[y+1][x+2] = true;
      q.push([y+1,x+2,c+1])
    }
    if(y-1>-1 && x+2<square && check(y-1,x+2)){
      isVisited[y-1][x+2] = true;
      q.push([y-1,x+2,c+1])
    }
    if(y+1<square && x-2>-1&& check(y+1,x-2)){
      isVisited[y+1][x-2] = true;
      q.push([y+1,x-2,c+1])
    }
    if(y-1>-1 && x-2>-1 && check(y-1,x-2)){
      isVisited[y-1][x-2] = true;
      q.push([y-1,x-2,c+1])
    }
  }
}

}

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