1. N Queen 문제
def check(a, row, col):
for r, c in enumerate(a):
if col == c or abs(col - c) == abs(row - r):
return False
return True
def recursive(row, a):
global result
if row == 4:
result.append(a[:])
return
for col in [0, 1, 2, 3]:
if check(a, row, col): # 가지치기 (이전 퀀의 위치에 따라 탐색 제외)
a.append(col)
recursive(row + 1, a)
a.pop()
result = []
recursive(0, [])
print(result) # [[1, 3, 0, 2], [2, 0, 3, 1]]
(참조) 위와 동일한 로직이지만, append, pop 사용하지 않도록 변경해봄
def check(a, row, col):
for r, c in enumerate(a[:row]):
if col == c or abs(col - c) == abs(row - r):
return False
return True
def recursive(row):
global result
if row == 4:
result.append(a[:])
return
for col in [0, 1, 2, 3]:
a[row] = col
if check(a, row, col): # 가지치기 (이전 퀀의 위치에 따라 탐색 제외)
recursive(row + 1)
a = [0] * 4
result = []
recursive(0)
print(result) # [[1, 3, 0, 2], [2, 0, 3, 1]]
'알고리즘 이론' 카테고리의 다른 글
1-4. [구현] 자주 사용하는 라이브러리 (0) | 2020.12.03 |
---|---|
3-2. [그래프 탐색] Kruskal, Prim (최소신장트리) (0) | 2020.10.03 |
3-1. [그래프 탐색] BFS (전체탐색) Dijkstra (최단거리) (0) | 2020.10.03 |
2-1. [정렬], [이분탐색] (0) | 2020.10.02 |
1-3. [구현] 수학 (0) | 2020.09.30 |