백준 5427. 불

2025. 1. 29. 15:16·백준

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

불! 이랑 똑같은 풀이 (상근이 먼저 이동 -> 불 이동)

import sys
from collections import deque
input = sys.stdin.readline

t = int(input())
for tc in range(t):
    w, h = map(int,input().split())
    arr = [list(input().rstrip()) for _ in range(h)]
    q = deque()
    ans = 'IMPOSSIBLE'

    # 상근이 먼저 이동
    for i in range(h):
        for j in range(w):
            if arr[i][j] == '@':
                q.append((0,i,j))
                break

    # 불 퍼짐
    for i in range(h):
        for j in range(w):
            if arr[i][j] == '*':
                q.append((-1,i,j))

    while q:
        cnt, i, j = q.popleft()

        if cnt > -1 and arr[i][j] != '*' and (i == 0 or j == 0 or i == h - 1 or j == w - 1):
            ans = cnt + 1
            break

        for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
            nx, ny = i + dx, j + dy
            if 0 <= nx < h and 0 <= ny < w and arr[nx][ny] != '#':

                if cnt > -1 and arr[nx][ny] == '.':
                    q.append((cnt+1,nx,ny))
                    arr[nx][ny] = '@'
                elif cnt == -1 and arr[nx][ny] != '*':
                    q.append((-1,nx,ny))
                    arr[nx][ny] = '*'
    print(ans)

시간 3분의 1로 줄인 다른 풀이(불 이동->상근이 이동)

import sys
from collections import deque
input = sys.stdin.readline

t = int(input())
for tc in range(t):
    w, h = map(int,input().split())
    arr = [list(input().rstrip()) for _ in range(h)]
    q = deque()
    fires = deque()

    for i in range(h):
        for j in range(w):
            if arr[i][j] == '@':
                q.append((0,i,j))
            elif arr[i][j] == '*':
                fires.append((i,j))

    def bfs(w, h, arr, q, fires):

        while q:
            for _ in range(len(fires)):
                f_i, f_j = fires.popleft()
                for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
                    nx, ny = f_i + dx, f_j + dy
                    if 0 <= nx < h and 0 <= ny < w and arr[nx][ny] == '.':
                        fires.append((nx, ny))
                        arr[nx][ny] = '*'

            for _ in range(len(q)):
                cnt, i, j = q.popleft()

                # 탈출 성공 1
                if i < 0 or i >= h or j < 0 or j >= w:
                    return cnt

                for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
                    nx, ny = i + dx, j + dy
                    
                    # 다음에 탈출 성공 2
                    if nx < 0 or nx >= h or ny < 0 or ny >= w:
                        return cnt + 1

                    if arr[nx][ny] == '.':
                        q.append((cnt+1,nx,ny))
                        arr[nx][ny] = '@'
        return "IMPOSSIBLE"

    print(bfs(w, h, arr, q, fires))
저작자표시 (새창열림)

'백준' 카테고리의 다른 글

백준 13549. 숨바꼭질 3  (0) 2025.01.31
백준 9466. 텀 프로젝트  (0) 2025.01.30
백준 10026. 적록색약  (0) 2025.01.29
10971. 외판원 순회 2  (0) 2025.01.28
백준 11724. 연결 요소의 개수  (0) 2025.01.28
'백준' 카테고리의 다른 글
  • 백준 13549. 숨바꼭질 3
  • 백준 9466. 텀 프로젝트
  • 백준 10026. 적록색약
  • 10971. 외판원 순회 2
버그잡는고양이발
버그잡는고양이발
주니어 개발자입니다!
  • 버그잡는고양이발
    지극히평범한개발블로그
    버그잡는고양이발
  • 전체
    오늘
    어제
    • 분류 전체보기 (382)
      • React (16)
      • Next.js (5)
      • Javascript (5)
      • Typescript (4)
      • Node.js (2)
      • Cs (16)
      • 트러블 슈팅 (5)
      • Html (1)
      • Css (3)
      • Django (0)
      • vue (0)
      • Java (2)
      • Python (0)
      • 독서 (1)
      • 기타 (3)
      • 백준 (192)
      • swea (31)
      • 프로그래머스 (30)
      • 이코테 (4)
      • 99클럽 코테 스터디 (30)
      • ssafy (31)
      • IT기사 (1)
  • 블로그 메뉴

    • 홈
    • 태그
  • 인기 글

  • 태그

    항해99
    Til
    코딩테스트준비
    99클럽
    개발자취업
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
버그잡는고양이발
백준 5427. 불
상단으로

티스토리툴바