카테고리 없음

BOJ 4993_Red and Black : BFS알고리즘 - 파이썬

2023. 11. 22. 18:30

문제

There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move only on black tiles.

Write a program to count the number of black tiles which he can reach by repeating the moves described above.

입력

The input consists of multiple data sets. A data set starts with a line containing two positive integers W and H; W and H are the numbers of tiles in the x- and y- directions, respectively. W and H are not more than 20.

There are H more lines in the data set, each of which includes W characters. Each character represents the color of a tile as follows.

  • '.' - a black tile
  • '#' - a red tile
  • '@' - a man on a black tile(appears exactly once in a data set)

The end of the input is indicated by a line consisting of two zeros.

출력

For each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).

 

제출코드

from collections import deque

# 이동할 네가지 방향 정의 (상하좌우)
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

def bfs(x, y):
    queue = deque()
    queue.append((a, b))
    graph[x][y] = 0  # 방문처리
    count = 1
    while queue:
        x, y = queue.popleft()

        for i in range(4):  # 4가지 방향으로 위치확인
            nx = x + dx[i]
            ny = y + dy[i]

            # 위치가 벗어나면 안되기 때문에 조건 추가
            if nx < 0 or nx >= H or ny < 0 or ny >= W:
                continue

            # 빨강타일이므로 진행 불가
            if graph[nx][ny] == "#":
                continue

            # 검정타일이므로 이동
            if graph[nx][ny] == ".":
                queue.append((nx, ny))
                graph[nx][ny] = 0
                count += 1

    return count

while True:
    W, H = map(int, input().split())
    graph = []

    if W == 0 and H == 0:
        break

    for _ in range(H):
        graph.append(list(map(str, input())))

    for a in range(H):
        for b in range(W):
            if graph[a][b] == "@":
                count = bfs(a, b)

    print(count)
저작자표시 (새창열림)
아아네잔
아아네잔
아아네잔
로깅
아아네잔
전체
오늘
어제
  • 분류 전체보기 (22)
    • Spring (2)
    • Docker (2)
    • Javascript (2)
    • Vue.js (4)
    • SQL (4)
    • MSSQL (1)
    • Others (2)
    • TroubleShooting (2)
    • tools (2)
    • #기술면접 (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 자바기술면접
  • 파일시스템변환
  • M1dockerdesktop
  • Notion
  • vuerouter3
  • 구글맞춤법검사기
  • 노션맞춤법검사해제
  • vue2
  • 자바장단점
  • 맞춤법검사
  • VARCHAR210Char #VARCHAR210
  • 뷰라우터
  • vue입력값초기화
  • NTFS변환
  • SQLD1장
  • vuerouter
  • 노션
  • vuerouter4
  • vuejs
  • 자바특징
  • 노션빨간줄
  • 웹서버만들기
  • SQLD핵심정리
  • modal컴포넌트초기화
  • docker
  • 이드라이브는손상되었기때문에변환할수없습니다
  • M1nginx
  • nginx

최근 댓글

최근 글

hELLO · Designed By 정상우.
아아네잔
BOJ 4993_Red and Black : BFS알고리즘 - 파이썬
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.