https://www.acmicpc.net/problem/14620
14620번: 꽃길
2017년 4월 5일 식목일을 맞이한 진아는 나무를 심는 대신 하이테크관 앞 화단에 꽃을 심어 등교할 때 마다 꽃길을 걷고 싶었다. 진아가 가진 꽃의 씨앗은 꽃을 심고나면 정확히 1년후에 꽃이 피므
www.acmicpc.net
풀이
이 문제는 파이썬의 itertools를 사용해서 combinations를 통해서 푸는 방법과 DFS로 푸는 방법이 있다.
코드
#=================== 조합으로 푸는 방법 ===================
# import itertools
# feild = []
# answer = int(10e9)
# d = [(-1, 0), (1, 0), (0, 1), (0, -1)]
# def calc(data):
# visited = []
# total = 0
# global answer
# for r, c in data:
# if (r,c) not in visited:
# visited.append((r,c))
# total += feild[r][c]
# for idx in range(4):
# nx = r + d[idx][0]
# ny = c + d[idx][1]
# if (nx, ny) not in visited:
# visited.append((nx, ny))
# total += feild[nx][ny]
# else: return
# else: return
# answer = min(answer, total)
# def sol():
# N = int(input())
# for i in range(N):
# feild.append(list(map(int, input().split(" "))))
# candidates = [(r, c) for r in range(1, N-1) for c in range(1, N-1)]
# for data in itertools.combinations(candidates, 3):
# calc(data)
# print(answer)
# sol()
#=================== DFS으로 푸는 방법 ===================
field = []
answer = int(1e9)
d = [(-1, 0), (1, 0), (0, -1), (0, 1)]
N = 0
def sol():
global N
N = int(input())
for _ in range(N):
field.append(list(map(int, input().split(" "))))
DFS([], 0)
print(answer)
def DFS(visited, total):
global answer
if total >= answer:
return
if len(visited) == 15:
answer = min(answer, total)
else:
for i in range(1, N-1):
for j in range(1, N-1):
if check(i, j, visited) and (i,j) not in visited:
temp = [(i,j)]
temp_cost = field[i][j]
for idx in range(4):
nx = i + d[idx][0]
ny = j + d[idx][1]
temp.append((nx, ny))
temp_cost += field[nx][ny]
DFS(visited + temp, total + temp_cost)
def check(i, j, visited):
for idx in range(4):
nx = i + d[idx][0]
ny = j + d[idx][1]
if (nx, ny) in visited: return False
return True
sol()
'백준' 카테고리의 다른 글
백준 2812 크게 만들기 (파이썬) (0) | 2023.07.06 |
---|---|
백준 4358 생태학 (파이썬) (0) | 2023.06.24 |
백준 2671 잠수함식별(파이썬) (0) | 2023.06.23 |
백준 1212 8진수 2진수 (파이썬) (0) | 2023.04.20 |
백준 20053 최소, 최대 2 (파이썬) (0) | 2023.04.20 |