๐Ÿ”Ž ๋ฏธ๋กœ ํƒ์ƒ‰

๋ฐฑ์ค€ Class3 Silver1

solved_ac[Class3] ๋ฏธ๋กœ ํƒ์ƒ‰

๋ฌธ์ œ

Nร—Mํฌ๊ธฐ์˜ ๋ฐฐ์—ด๋กœ ํ‘œํ˜„๋˜๋Š” ๋ฏธ๋กœ๊ฐ€ ์žˆ๋‹ค.

แ„‰แ…ณแ„แ…ณแ„…แ…ตแ†ซแ„‰แ…ฃแ†บ 2022-07-07 แ„‹แ…ฉแ„’แ…ฎ 12 59 39

๋ฏธ๋กœ์—์„œ 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

๐Ÿ›  ์ž๋ฃŒ๊ตฌ์กฐ

์ด ๋ฌธ์ œ๋Š” BFS๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค. ์™œ๋ƒํ•˜๋ฉด โ€œํŠน์ • ๋…ธ๋“œ์—์„œ ํŠน์ • ๋…ธ๋“œ๊นŒ์ง€์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ & Weight ์—†์Œโ€์ด๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

แ„‰แ…ณแ„แ…ณแ„…แ…ตแ†ซแ„‰แ…ฃแ†บ 2022-07-10 แ„‹แ…ฉแ„Œแ…ฅแ†ซ 7 08 47

BFS๋กœ ๊ทธ๋ž˜ํ”„ ์ „์ฒด๋ฅผ ํƒ์ƒ‰ํ•˜๋ฉฐ (0,0) ์œ„์น˜๋กœ๋ถ€ํ„ฐ ์ด๋™ ์นธ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜๊ณ  ์ตœ์ข… ํƒ์ƒ‰์ด ์ข…๋ฃŒ๋˜์—ˆ์„ ๋•Œ (N-1,M-1)์œ„์น˜์˜ ์ด๋™ ์นธ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

๋ฌธ์ œ์—์„œ๋Š” ์‹œ์ž‘์ ์ด (1,1) ์ข…๋ฃŒ์ ์ด (N,M)์ด์ง€๋งŒ ๋ฐฐ์—ด์˜ index๊ฐ€ (0,0)๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๋ฏ€๋กœ ์ด๋ฅผ ๊ณ ๋ คํ•˜์˜€๋‹ค.

๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ป CODE

from collections import deque
N,M = map(int,input().split())

# ๋ฏธ๋กœ ์ดˆ๊ธฐํ™”
graph = [[0]*M for _ in range(N)]

# ๋ฏธ๋กœ ์ •๋ณด ์ž…๋ ฅ
for i in range(N):
    line = input()
    for j in range(M):
       graph[i][j] = int(line[j])

dx = [1,-1,0,0]
dy = [0,0,1,-1]

# BFS
def bfs(x,y):
    q = deque([(x,y)])
    
    while q:
        cur = q.popleft()
        ox,oy = cur[0],cur[1]

        # ์ •๋‹ต์„ ์ฐพ์€ Case
        if cur == (N-1,M-1):
            break

        # ์ •๋‹ต์„ ์ฐพ์•„๊ฐ€๋Š” ๊ณผ์ •
        for i in range(4):
            nx = cur[0]+dx[i]
            ny = cur[1]+dy[i]

            if 0<=nx<N and 0<=ny<M and graph[nx][ny] == 1:
                q.append((nx,ny))
                graph[nx][ny] = graph[ox][oy] + 1

bfs(0,0)

print(graph[N-1][M-1])

ยฉ 2022. All rights reserved.

Powered by Hydejack v9.1.6