[python]섬의 둘레구하기

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
direction = ((-1,0), (1,0), (0, -1), (0, 1))

def sol(st_y, st_x):
    global w, h
    cnt = 0
    for d in direction:
        next_y = st_y + d[0]
        next_x = st_x + d[1]
        if next_y<0 or next_y>=h or next_x<0 or next_x>=w or MAP[next_y][next_x] == 0:
            cnt += 1
    return cnt

while True:
    w, h = map(int, input().split())
    if (w, h) == (0, 0):
        break
    MAP = [list(map(int, input().split())) for _ in range(h)]

    answer = 0
    for i in range(h):
        for j in range(w):
            if MAP[i][j] == 0:
                continue
            answer += sol(i,j)

    print(answer)
아이디어는 단순하다. 모든 좌표를 순회하면서 주변이 땅으로 연결되지 않을때 cnt를 하나씩 증가시킨다.

댓글

  1. # sample input
    1 1
    0
    2 2
    0 1
    1 0
    3 2
    1 1 1
    1 1 1
    5 4
    1 0 1 0 0
    1 0 0 0 0
    1 0 1 0 1
    1 0 0 1 0
    5 4
    1 1 1 0 1
    1 0 1 0 1
    1 0 1 0 1
    1 0 1 1 1
    5 5
    1 0 1 0 1
    0 0 0 0 0
    1 0 1 0 1
    0 0 0 0 0
    1 0 1 0 1
    0 0

    # sample output
    0
    8
    10
    26
    30
    36

    답글삭제

댓글 쓰기

이 블로그의 인기 게시물

백트래킹으로 부분집합구하기(Get Powerset usiing Backtracking)

[패턴매칭][Python]보이어 무어 알고리즘