태그 : bfs

미로 탐색

문제

N×M크기의 배열로 표현되는 미로가 있다.

1	0	1	1	1	1
1	0	1	0	1	0
1	0	1	0	1	1
1	1	1	0	1	1

미로에서 1은 이동할 수 있는 칸을 나타내고, 0은 이동할 수 없는 칸을 나타낸다. 이러한 미로가 주어졌을 때, (1, 1)에서 출발하여 (N, M)의 위치로 이동할 때 지나야 하는 최소의 칸 수를 구하는 프로그램을 작성하시오. 한 칸에서 다른 칸으로 이동할 때, 서로 인접한 칸으로만 이동할 수 있다.

위의 예에서는 15칸을 지나야 (N, M)의 위치로 이동할 수 있다. 칸을 셀 때에는 시작 위치와 도착 위치도 포함한다.

입력

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

출력

첫째 줄에 지나야 하는 최소의 칸 수를 출력한다. 항상 도착위치로 이동할 수 있는 경우만 입력으로 주어진다.

입출력 예제

//입력1
4 6
101111
101010
101011
111011
//출력1
15
//입력2
4 6
110110
110110
111111
111101
//출력2
9
//입력3
2 25
1011101110111011101110111
1110111011101110111011101
//출력3
38
//입력4
7 7
1011111
1110001
1000001
1000001
1000001
1000001
1111111
//출력4
13
👍 #1. 풀이확인 js 👍
 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
32
33
34
35
36
37
38
39
40
41
let readline = require('readline')
const r = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})
let input = []
r.on('line', (line) => {
  input.push(line)
}).on('close', () => {
  const [N, M] = input[0].toString().trim().split(/\s+/).map(n => +n)
  const maze = input.slice(1).map(i => i.toString().trim().split('').map(i => +i))
  const dx = [0, 0, -1, 1]
  const dy = [-1, 1, 0, 0]

  let countMatrix = Array(N).fill().map(i => Array(M).fill(0))
  let visitedMatrix = Array(N).fill().map(i => Array(M).fill(false))
  let result = []
  const bfs = (start) => {
    let queue = []
    queue.push(start)
    while (queue.length) {
      const [x, y] = queue[0]
      result.push(queue.shift())
      visitedMatrix[x][y] = true
      for (let k = 0; k < 4; k++) {
        let nx = x + dx[k]
        let ny = y + dy[k]
        if (nx >= 0 && nx < N && ny >= 0 && ny < M) {
          if (!visitedMatrix[nx][ny] && maze[nx][ny] !== 0) {
            queue.push([nx, ny])
            maze[nx][ny] = maze[x][y] + 1
            visitedMatrix[nx][ny] = true
          }
        }
      }
    }
  }
  bfs([0, 0])
  console.log(maze[N - 1][M - 1])
  process.exit()
})

최소칸 수를 구하는 프로그램이라고 해서 프로이드 와샬을 사용하려고 했는데, (2<=N,M<=100) 이라고 할때 만약 100 X 100이라면 노드가 10000개 이고 이것의 3제곱은 이미 1억을 넘어가서 시간초과가 일어날것이라 생각해서 BFS로 접근해보려고 했음.

그래프를 이용할 때 키값을 배열로 넣을수가 없어서 고민이 많았다.

근데 bfs를 이용할때 꼭 그래프 클래스를 만들어서 할 필요는 없다는걸 깨달음….큐만을 이용하면 되는것을…

아래는 결국 그래프를 이용해서 bfs를 구현하였지만, 최소 칸수를 구하지 못한 코드.

👍 #. 실패코드 👍
 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
  let input = require('fs').readFileSync('/dev/stdin')
let data = input.toString().trim().split(/\n+/).map(i => [...i.toString().trim()].map(n => +n))
class Graph {
  constructor() {
    this.nodeList = new Map()
    this.adjList = new Map()
  }

  addNode (node, value) {
    if (!this.nodeList.has(node)) {
      this.nodeList.set(node, value)
    }
  }

  addEdge (pre, post) {
    if (!this.adjList.has(pre)) {
      this.adjList.set(pre, [post])
    } else {
      this.adjList.get(pre).push(post)
    }
  }
}

// set adjList
const setAdjList = (value, node) => {
  const [x, y] = value
  // left
  if ((y - 1 >= 0)) {
    graph.addEdge(node, node - 1)
  }
  // right
  if (y + 1 < M) {
    graph.addEdge(node, node + 1)
  }
  // up
  if (x - 1 >= 0) {
    graph.addEdge(node, node - M)
  }
  // down
  if (x + 1 < N) {
    graph.addEdge(node, node + M)
  }
}

const bfs = (start) => {
  let queue = []
  let result = []
  let visited = new Map()
  queue.push(start)
  visited.set(start, true)
  while (queue.length) {
    const first = queue[0]
    result.push(queue.shift())
    if (first === graph.nodeList.size - 1) break
    if (graph.adjList.get(first) && graph.adjList.get(first).length) {
      graph.adjList.get(first).forEach(node => {
        const [x, y] = graph.nodeList.get(node)
        if (maze[x][y] === 1 && !visited.get(node)) {
          queue.push(node)
          map[x][y]
          visited.set(node, true)
        }
      })
    }
  }
  return result
}

const graph = new Graph()

let node = 0
// set nodeList
for (let i = 0; i < N; i++) {
  for (let j = 0; j < M; j++) {
    graph.addNode(node, [i, j])
    node++
  }
}

graph.nodeList.forEach((value, node) => {
  setAdjList(value, node)
})
console.log(bfs(0))
◀️ 단지번호붙이기 맥주 마시면서 걸어가기 ▶️
comments powered by Disqus