Computer science/Algorithm

[파이썬] 달팽이

잔망루피 2021. 11. 4. 19:34
반응형
r=4
c=4
matrix=[
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15,16]
]

# 우 하 좌 상
dx=[0, 1, 0, -1]
dy=[1, 0, -1, 0]

x=0
y=0
pos=0
visited=[[0]*c for _ in range(r)]
visited[0][0]=1
cnt=1
print(1, end=" ")

while cnt < r*c :
    nx = x + dx[pos]
    ny = y + dy[pos]
    if 0 <= nx < r and 0 <= ny < c and not visited[nx][ny] :
        visited[nx][ny] = 1
        print(matrix[nx][ny], end=" ")
        cnt += 1
        x, y = nx, ny
    else :
        pos=(pos+1)%4

1부터 시작해 시계방향으로 출력했다.

visited로 방문기록을 해야 같은 숫자를 출력하지 않는다.

pos=(pos+1)%4로 방향을 바꿔주었다.

리스트에 출력할 값을 차례로 담은 뒤 출력해주는 게 더 깔끔했을 것 같다.

반응형

'Computer science > Algorithm' 카테고리의 다른 글

이진탐색  (0) 2022.01.06
palindrome  (0) 2021.12.06
문자열 비교  (0) 2021.10.17
Sliding window와 Two pointer algorithm  (0) 2021.10.11
비트마스크  (0) 2021.09.25