ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [๋ฐฑ์ค€] 13565 ์นจํˆฌ with Python
    PS 2022. 2. 19. 18:10
    728x90
    ๋ฐ˜์‘ํ˜•

    ๐Ÿ“Œ BOJ 13565 ์นจํˆฌ

    ๐Ÿ’ก ์กฐ๊ฑด

    1. ๊ฒฉ์ž์˜ ํฌ๊ธฐ๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” M (2 โ‰ค M โ‰ค 1,000) ๊ณผ N (2 โ‰ค N โ‰ค 1,000)

    2. M์ค„์— ๊ฑธ์ณ์„œ, N๊ฐœ์˜ 0 ๋˜๋Š” 1 ์ด ๊ณต๋ฐฑ ์—†์ด ์ฃผ์–ด์ง„๋‹ค. 0์€ ์ „๋ฅ˜๊ฐ€ ์ž˜ ํ†ตํ•˜๋Š” ํฐ์ƒ‰, 1์€ ์ „๋ฅ˜๊ฐ€ ํ†ตํ•˜์ง€ ์•Š๋Š” ๊ฒ€์€์ƒ‰ ๊ฒฉ์ž์ž„์„ ๋œปํ•œ๋‹ค.

    3. ๋งจ ์œ—์ค„์—์„œ ๋ฐ›์€ ์ „๊ธฐ๊ฐ€ ๋งจ ๋ฐ‘ ์ค„๊นŒ์ง€ ๊ฐˆ ์ˆ˜ ์žˆ๋‹ค๋ฉด True, ์•„๋‹ˆ๋ฉด False

    4. BFS ์œ ํ˜•์˜ ๋ฌธ์ œ

    ๐Ÿ–ฅ ์†Œ์Šค ์ฝ”๋“œ

    from sys import stdin
    from collections import deque
    
    n, m = map(int, stdin.readline().split())
    board = []
    visited = set()
    for _ in range(n):
        board.append(list(map(int, list(stdin.readline().rstrip()))))
    
    dx, dy = [0, 0, -1, 1], [1, -1, 0, 0]
    res_tf = False
    
    
    def bfs(x, y):
        q = deque()
        q.append((x, y))
        visited.add((x, y))
    
        while q:
            x, y = q.popleft()
            if x == n - 1:
                return True
    
            for i in range(4):
                nx, ny = dx[i] + x, dy[i] + y
                if -1 < nx < n and -1 < ny < m and (nx, ny) not in visited:
                    if board[nx][ny] == 0:
                        q.append((nx, ny))
                        visited.add((nx, ny))
    
    
    for j in range(m):
        if board[0][j] == 0 and (0, j) not in visited:
            if bfs(0, j) is True:
                res_tf = True
                break
    
    print('YES') if res_tf else print('NO')

    ๐Ÿ”– ์˜ˆ์ œ ๋ฐ ์‹คํ–‰๊ฒฐ๊ณผ

    ์˜ˆ์ œ

    5 6
    010101
    010000
    011101
    100011
    001011

    ์‹คํ–‰๊ฒฐ๊ณผ

    NO

    โŒจ๏ธ ๋ฌธ์ œ ํ’€์ด

    1. ์ „๋ฅ˜ํŒ์„ board ๋ฆฌ์ŠคํŠธ์— ์ž…๋ ฅ๋ฐ›์•„ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.
      ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ๋ฅผ ํ•  visited ๋ฅผ set() ์ž๋ฃŒํ˜•์œผ๋กœ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.

    2. bfs ํ•จ์ˆ˜๋Š” ๋„ˆ๋น„์šฐ์„ ํƒ์ƒ‰์˜ ๋กœ์ง์„ ๊ธฐ๋ณธ์ ์œผ๋กœ๋งŒ ๊ตฌํ˜„ํ•œ ํ˜•ํƒœ์ž…๋‹ˆ๋‹ค.
      ์ƒํ•˜์ขŒ์šฐ๋กœ ์›€์ง์ด๋ฉด์„œ ํ์— ๋‹ค์Œ ์ด๋™ํ•  ์ขŒํ‘œ๋ฅผ ๋„ฃ์œผ๋ฉฐ, ์ด๋™ํ•  ์ˆ˜ ์žˆ๋Š” ์ขŒํ‘œ๋ฅผ ํ์— ๋„ฃ์—ˆ์„ ๋• visited ์— ๋„ฃ์–ด์ค๋‹ˆ๋‹ค.
      ๋งŒ์•ฝ n - 1 ๊ณผ ํ˜„์žฌ ํ์—์„œ ๋ฝ‘์€ x ์ขŒํ‘œ์˜ ๊ฐ’์ด ๊ฐ™๋‹ค๋ฉด ๋งจ ๋ฐ‘์œผ๋กœ ์ „๋ฅ˜๊ฐ€ ์ „๋‹ฌ ๋œ ๊ฒƒ์ด๋‹ˆ true ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
      ์•„๋‹ˆ๋ผ๋ฉด None ์ด ๋ฐ˜ํ™˜๋ฉ๋‹ˆ๋‹ค.

    3. ๊ฐ€์žฅ ์œ—์ค„์„ ๋ณผ ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— m๋งŒํผ ์ˆœํšŒ๋ฅผ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.(j)
      borad[0][i] ๊ฐ€ 0์ด๊ณ  (0, j) ์ขŒํ‘œ๊ฐ€ ์ด๋ฏธ ๊ฒ€์‚ฌํ•œ ์ขŒํ‘œ๊ฐ€ ์•„๋‹ˆ๋ผ๋ฉด bfs์— ๋„ฃ์Šต๋‹ˆ๋‹ค.

    4. bfs์˜ ๊ฒฐ๊ณผ ๊ฐ’์ด true๊ฐ€ ๋ฐ˜ํ™˜๋˜์—ˆ๋‹ค๋ฉด res_tf ๋ฅผ true๋กœ ๊ฐฑ์‹ ํ•˜๊ณ  ์ˆœํšŒ๋ฅผ ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค.

    5. res_tf ๊ฐ€ true ๋ผ๋ฉด YES, ์•„๋‹ˆ๋ผ๋ฉด NO ๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค

    ๐Ÿ’พ ๋Š๋‚€์ 

    1. ๊ฐ„๋‹จํ•œ ๋„ˆ๋น„์šฐ์„ ํƒ์ƒ‰์˜ ๋ฌธ์ œ์˜€์Šต๋‹ˆ๋‹ค.
    ๋ฐ˜์‘ํ˜•

    ๋Œ“๊ธ€

Designed by Tistory.