๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“– Problem Solution/Programmers

[JS] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๊ฒŒ์ž„ ๋งต ์ตœ๋‹จ๊ฑฐ๋ฆฌ

by Fomagran ๐Ÿ’ป 2022. 4. 11.
728x90
๋ฐ˜์‘ํ˜•

 

Problem

 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๊ฒŒ์ž„ ๋งต ์ตœ๋‹จ๊ฑฐ๋ฆฌ

[[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,1],[0,0,0,0,1]] 11 [[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,0],[0,0,0,0,1]] -1

programmers.co.kr


Solution

 

ํ•ด๋‹น ๋ฌธ์ œ๋Š” BFS๋กœ ํ’€์–ด์•ผ ํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

 

1. ์ดˆ๊ธฐ ํ–‰๊ณผ ์—ด์˜ ๊ฐฏ์ˆ˜๋ฅผ ์ €์žฅํ•œ๋‹ค.

 

    const N = maps.length
    const M = maps[0].length

 

2. ์ƒํ•˜์ขŒ์šฐ๋กœ ์›€์ง์ผ x์™€ y์˜ ๊ฐ’์„ ์ €์žฅํ•œ๋‹ค.

 

    const direction = [[0, -1], [0, 1], [-1, 0], [1, 0]]

 

3. ๋งต์˜ ๊ฐ€์žฅ์ž๋ฆฌ๋ฅผ ํ•œ ๊ฒน ๊ฐ์‹ธ์ค€๋‹ค.

 

๋งต์˜ ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜๊ฒŒ ๋˜๋ฉด 0์œผ๋กœ ๊ฐ„์ฃผํ•  ์ˆ˜ ์žˆ๊ฒŒ ๊ฐ€์žฅ ์ž๋ฆฌ๋ฅผ ๊ฐ์‹ธ์ค๋‹ˆ๋‹ค.

 

    let map = maps
    wrapEdges(map)

 

์—ด์˜ 0๋ฒˆ์งธ์™€ ๋งจ ๋๋ฒˆ์งธ, ํ–‰์˜ 0๋ฒˆ์งธ์™€ ๋งจ ๋๋ฒˆ์งธ์— 0์„ ๋„ฃ์–ด์ค๋‹ˆ๋‹ค.

 

function wrapEdges(maps) {
    for (m of maps) {
        m.splice(0, 0, 0);
        m.push(0)
    }
    maps.splice(0, 0, new Array(maps.length + 2).fill(0));
    maps.push(new Array(maps.length + 1).fill(0));
}

 

4. BFS๋กœ ๊ฐ ๋ฐฉํ–ฅ์œผ๋กœ ์›€์ง์ผ ์ˆ˜ ์žˆ๊ฒŒ ์ง„ํ–‰ํ•œ๋‹ค.

 

queue๋ฅผ ๋งŒ๋“ค๊ณ  ์‹œ์ž‘์ ์˜ ์œ„์น˜์™€ ์›€์ง์ธ ํšŸ์ˆ˜๋ฅผ ๋„ฃ์–ด์ค๋‹ˆ๋‹ค.

 

map์— ์‹œ์ž‘ ์ง€์ ์„ 0์œผ๋กœ ๋งŒ๋“ค์–ด ์ค๋‹ˆ๋‹ค.

 

  let queue = [[1, 1, 1]]
  map[1][1] = 0

 

queue์—์„œ ์ฒซ ๋ฒˆ์งธ ๊ฐ’์„ ๊บผ๋‚ด์–ด ๋ชฉํ‘œ ์ง€์ (N,M)์— ๋„์ฐฉํ•˜์˜€๋‹ค๋ฉด ์›€์ง์ธ ํšŸ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•ด ์ค๋‹ˆ๋‹ค.

 

๊ทธ๊ฒŒ ์•„๋‹ˆ๋ผ๋ฉด  ๊ฐ ๋ฐฉํ–ฅ๋งˆ๋‹ค ์บ๋ฆญํ„ฐ์˜ ์œ„์น˜๋ฅผ ๋ฐ”๊ฟ” ์ง„ํ–‰ํ•ด ์ค๋‹ˆ๋‹ค.

 

๋‹จ, ๋ฌดํ•œ ๋ฃจํ”„๋ฅผ ๋ง‰๊ธฐ ์œ„ํ•ด ์ด๋ฏธ ๋ฐฉ๋ฌธํ•˜์˜€๋‹ค๋ฉด ํ•ด๋‹น ์œ„์น˜๋ฅผ 0์œผ๋กœ ๋ฐ”๊ฟ”์ค๋‹ˆ๋‹ค.

 

    while (queue.length > 0) {
        const [x,y,count] = queue.shift()
        if (x == N && y == M) {
            return count
        }

        for (d of direction) {
            const next = [x + d[0],y + d[1],count+1]
            if (map[next[0]][next[1]] === 1) {
            map[next[0]][next[1]] = 0
            queue.push(next)
            }
        }
    }

 

5. ์บ๋ฆญํ„ฐ๊ฐ€ ๋ชฉํ‘œ ์ง€์ ์„ ์˜ค์ง€ ๋ชปํ•œ๋‹ค๋ฉด -1์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

 

while๋ฌธ ์•ˆ์—์„œ return์ด ๋ฐœ์ƒํ•˜์ง€ ์•Š์•˜๋‹ค๋ฉด ๋ชฉํ‘œ ์ง€์ ์„ ์˜ค์ง€ ๋ชปํ•œ ๊ฒƒ์ด๋ฏ€๋กœ -1์„ ๋ฐ˜ํ™˜ํ•ด ์ค๋‹ˆ๋‹ค.

 

    return -1

Source Code

 


P.S

 

์˜ค๋žœ๋งŒ์— JS๋กœ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ํ’€์—ˆ๋Š”๋ฐ Swift์™€ ๊ฐ™์ด struct๋ฅผ ๋งŒ๋“ค์ง€ ๋ชปํ•ด map์„ ์ด์šฉํ•ด ๊ฐ์ฒด์ฒ˜๋Ÿผ ํ’€์—ˆ๋Š”๋ฐ ๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค.

 

์˜ˆ๋ฅผ ๋“ค๋ฉด ๋ฐฉํ–ฅ์„ ์ •ํ•  ๋•Œ {x:0,y:1}, ํ ์•ˆ์— ๋“ค์–ด๊ฐˆ ์ •๋ณด๋„ {x:0,y1,count:1} ์ด๋Ÿฐ ์‹์œผ๋กœ ํ’€์—ˆ๋Š”๋ฐ ๋‹ค์Œ๋ถ€ํ„ฐ๋Š” ๊ทธ๋ƒฅ ๋ฐฐ์—ด๋กœ ํ’€์–ด์•ผ๊ฒ ๋‹ค..

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€