티스토리 뷰

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

 

2178번: 미로 탐색

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

www.acmicpc.net

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



miro.unshift(new Array(C).fill(0));
miro.push(new Array(C).fill(0));

miro.forEach((_,i)=>{
  miro[i].unshift(0);
  miro[i].push(0);
})


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

const q = new Queue();

q.push([1,1,1])

while(!q.empty()){
  let [y,x,c] = q.pop();
  
  if(y==R && x==C){
    console.log(c);
    break;
  }

  if(miro[y-1][x]==1){
    miro[y-1][x]=0;
    q.push([y-1,x,c+1])
  }
  if(miro[y+1][x]==1){
    miro[y+1][x]=0;
    q.push([y+1,x,c+1])
  }
  if(miro[y][x-1]==1){
    miro[y][x-1]=0;
    q.push([y,x-1,c+1])
  }
  if(miro[y][x+1]==1){
    miro[y][x+1]=0;
    q.push([y,x+1,c+1])
  }
}
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
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
글 보관함