인프런 영문 브랜드 로고
인프런 영문 브랜드 로고

Inflearn Community Q&A

jaeyung10011451's profile image
jaeyung10011451

asked

Introduction to Python Algorithm Problem Solving (Coding Test Preparation)

14. Safe Zone (DFS)

다음과 같이 풀어보았는데 상태체크배열이 안 변하는것 같습니다

Written on

·

173

0

제가 선언한 ch배열이 안바뀌고있는것같네요 혹시 어디가 문제인지 짚어주실수있으신가요? (0의 개수를 세는게 되버리네요...)

def DFS(x,y):
    ch[x][y] = 1
    for i in range(4):
        tx = x + dx[i]
        ty = y + dy[i]
        if 0<= tx < n and 0 <= ty < n and a[tx][ty] == 0:
            DFS(tx, ty)
    

dx = [-1, 0, 1, 0] # 방향 x축
dy = [0, 1, 0, -1] # 방향 y축
n = 5
a = [
    [6,8,2,6,2],
    [3,2,3,4,6],
    [6,7,3,3,2],
    [7,2,5,3,6],
    [8,9,5,2,7]
]

max_top = 0
min_top = 300
for i in range(n):
    for j in range(n):
        if a[i][j] > max_top:
            max_top = a[i][j]
        if a[i][j] < min_top:
            min_top = a[i][j]
            
print(max_top, min_top)

for i in range(min_top, max_top):
    cnt = 0
    ch = [[0]*n for _ in range(n)]
    for j in range(n):
        for z in range(n):
            if a[j][z] <= i:
                ch[j][z] = 1
                
    print(f'=========={i}==========')
    for k in ch:
        print(k)
    print()
    
    for j in range(n):
        for z in range(n):
            if ch[j][z] == 0:
                cnt += 1
                DFS(j,z)

    print('ISLAND:', cnt)


"""출력결과
9 2
==========2==========
[0, 0, 1, 0, 1]
[0, 1, 0, 0, 0]
[0, 0, 0, 0, 1]
[0, 1, 0, 0, 0]
[0, 0, 0, 1, 0]

ISLAND: 19
==========3==========
[0, 0, 1, 0, 1]
[1, 1, 1, 0, 0]
[0, 0, 1, 1, 1]
[0, 1, 0, 1, 0]
[0, 0, 0, 1, 0]

ISLAND: 14
==========4==========
[0, 0, 1, 0, 1]
[1, 1, 1, 1, 0]
[0, 0, 1, 1, 1]
[0, 1, 0, 1, 0]
[0, 0, 0, 1, 0]

ISLAND: 13
==========5==========
[0, 0, 1, 0, 1]
[1, 1, 1, 1, 0]
[0, 0, 1, 1, 1]
[0, 1, 1, 1, 0]
[0, 0, 1, 1, 0]

ISLAND: 11
==========6==========
[1, 0, 1, 1, 1]
[1, 1, 1, 1, 1]
[1, 0, 1, 1, 1]
[0, 1, 1, 1, 1]
[0, 0, 1, 1, 0]

ISLAND: 6
==========7==========
[1, 0, 1, 1, 1]
[1, 1, 1, 1, 1]
[1, 1, 1, 1, 1]
[1, 1, 1, 1, 1]
[0, 0, 1, 1, 1]

ISLAND: 3
==========8==========
[1, 1, 1, 1, 1]
[1, 1, 1, 1, 1]
[1, 1, 1, 1, 1]
[1, 1, 1, 1, 1]
[1, 0, 1, 1, 1]

ISLAND: 1
"""
python코테 준비 같이 해요!

Answer 2

0

jaeyung10011451님의 프로필 이미지
jaeyung10011451
Questioner

아 이런... ㅠㅠ 네 해결됐습니다 감사합니다 선생님~

0

codingcamp님의 프로필 이미지
codingcamp
Instructor

안녕하세요^^

if 0<= tx < n and 0 <= ty < n and a[tx][ty] == 0:

위 코드에 잘못이 있습니다.

jaeyung10011451's profile image
jaeyung10011451

asked

Ask a question