백준 온라인 저지, DFS / 13565번: 침투 (파이썬 / , 백준 실버문제)

2021. 12. 16. 00:04알고리즘/DFS

728x90
반응형

문제

인제대학교 생화학연구실에 재직중인 석교수는 전류가 침투(percolate) 할 수 있는 섬유 물질을 개발하고 있다. 이 섬유 물질은 2차원 M × N 격자로 표현될 수 있다. 편의상 2차원 격자의 위쪽을 바깥쪽(outer side), 아래쪽을 안쪽(inner side)라고 생각하기로 한다. 또한 각 격자는 검은색 아니면 흰색인데, 검은색은 전류를 차단하는 물질임을 뜻하고 흰색은 전류가 통할 수 있는 물질임을 뜻한다. 전류는 섬유 물질의 가장 바깥쪽 흰색 격자들에 공급되고, 이후에는 상하좌우로 인접한 흰색 격자들로 전달될 수 있다.

김 교수가 개발한 섬유 물질을 나타내는 정보가 2차원 격자 형태로 주어질 때, 바깥쪽에서 흘려 준 전류가 안쪽까지 침투될 수 있는지 아닌지를 판단하는 프로그램을 작성하시오.

(a) The current percolates. (b) The current does not percolate.

예를 들어, Figure 1(a) 에서는 바깥쪽에서 공급된 전류가 안쪽까지 침투하지만, Figure 1(b)에서는 그렇지 못한다.

입력

첫째 줄에는 격자의 크기를 나타내는  M (2 ≤ M ≤ 1,000) 과 N (2 ≤ N ≤ 1,000) 이 주어진다. M줄에 걸쳐서, N개의 0 또는 1 이 공백 없이 주어진다. 0은 전류가 잘 통하는 흰색, 1은 전류가 통하지 않는 검은색 격자임을 뜻한다.

출력

바깥에서 흘려준 전류가 안쪽까지 잘 전달되면 YES를 출력한다.

그렇지 않으면 NO를 출력한다.

예제 입력 1

5 6
010101
010000
011101
100011
001011

예제 출력 1

NO

예제 입력 2

8 8
11000111
01100000
00011001
11001000
10001001
10111100
01010000
00001011

예제 출력 2

YES
W3sicHJvYmxlbV9pZCI6IjEzNTY1IiwicHJvYmxlbV9sYW5nIjoiMCIsInRpdGxlIjoiXHVjZTY4XHVkMjJjIiwiZGVzY3JpcHRpb24iOiI8cD5cdWM3NzhcdWM4MWNcdWIzMDBcdWQ1N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CBpbnB1dC4gVGhlIGZpcnN0IGxpbmUgb2YgdGhlIGlucHV0IGNvbnRhaW5zIHR3byBpbnRlZ2VycyBNICgyICZsZTsgTSAmbGU7IDEsMDAwKSBhbmQgTiAoMiAmbGU7IE4gJmxlOyAxLDAwMCkgd2hpY2ggcmVwcmVzZW50IHRoZSBzaXplIG9mIHRoZSBmYWJyaWMuIEluIHRoZSBmb2xsb3dpbmcgTSBsaW5lcywgdGhlIGluZm9ybWF0aW9uIGFib3V0IGVhY2ggY2VsbCBpcyBnaXZlbi4gRWFjaCBsaW5lIGNvbnNpc3RzIG9mIE4gY2hhcmFjdGVycyB3aGljaCBjb21wb3NlZCBieSAmbHNxdW87MCZyc3F1bzsgb3IgJmxzcXVvOzEmcnNxdW87LiBUaGUgY2hhcmFjdGVyICZsc3F1bzswJnJzcXVvOyByZXByZXNlbnRzIHRoZSBjb25kdWN0IGNlbGwgYW5kICZsc3F1bzsxJnJzcXVvOyByZXByZXNlbnRzIHRoZSBpbnN1bGF0ZSBjZWxsLjxcL3A+XHJcbiIsIm91dHB1dCI6IjxwPllvdXIgcHJvZ3JhbSBpcyB0byB3cml0ZSB0byBzdGFuZGFyZCBvdXRwdXQuIElmIHRoZSBjdXJyZW50IGNhbiBwYXNzIHRocm91Z2ggdGhlIG1hdGVyaWFsIGZyb20gdGhlIHRvcCB0byB0aGUgYm90dG9tLCBwcmludCBZRVMuIElmIG5vdCwgcHJpbnQgTk8uPFwvcD5cclxuIiwiaGludCI6IiIsIm9yaWdpbmFsIjoiMSIsImh0bWxfdGl0bGUiOiIwIiwicHJvYmxlbV9sYW5nX3Rjb2RlIjoiRW5nbGlzaCJ9XQ==

접근 방법

- DFS 탐색을 통해 첫번째 행에서 출발해 마지막 행에 도착하는지 판단한다.
- 만일 도착한다면 YES, 끝까지 도착하지 못한다면 NO를 출력한다.

코드

# https://www.acmicpc.net/problem/13565
# 접근 방법
# DFS 탐색을 통해 첫번째 행에서 출발해 마지막 행에 도착하는지 판단한다.
# 만일 도착한다면 YES, 끝까지 도착하지 못한다면 NO를 출력한다.
import sys
sys.setrecursionlimit(10**6)
def dfs(r, c):
    if r == m-1:
        return True
    for dr, dc in [[1, 0], [-1, 0], [0, 1], [0, -1]]:
        if 0<=r+dr
728x90
반응형