본문 바로가기

Algorithm

(66)
7562 나이트의 이동 / DFS, BFS 정답나이트가 이동할 수 있는 경우의 수를 처음에 아래와 같이 했더니 오답이 나옴 dx = [-1, 1, 1, 2, -1, -2, 2, 1] dy = [2, -2, 2, 1, -2, -1, -1, -2] 다른 정답들을 찾아봐도 이해할 수 가 없어서 시계방향대로 이동할 수 있는 경로를 바꿨더니 정답이 나옴 dx = [-2, -1, 1, 2, 2, 1, -1, -2] dy = [1, 2, 2, 1, -1, -2, -2, -1] BFS에서 최단 경로 문제를 풀 땐 또는 방향 순서를 안정된 기준(예: 시계 방향) 으로 맞춰줘야 함from collections import dequecase = int(input())ans = []for _ in range(case): n = int(inp..
5014 스타트링크 / DFS, BFS 정답숨바꼭질이랑 비슷한 문제하나의 그래프에서 최소거리로 탐색한다고 보면 됨from collections import dequef, s, g, u, d = map(int, input().split()) # 건물의 총 수, 현재 위치, 회사 위치, 위로 u층, 아래로 d층distance = [0] * (f + 1)visited = [False] * (f + 1)def BFS(s): queue = deque() queue.append(s) visited[s] = True while queue: current = queue.popleft() if current == g: return distance[current] for next i..
1926 그림 / DFS, BFS 정답from collections import dequen, m = map(int, input().split()) # 세로 크기(높이), 가로 크기graph = []for _ in range(n): row = list(map(int, input().split())) graph.append(row)# 상하좌우 세팅dx = [-1, 1, 0, 0]dy = [0, 0, -1, 1]def BFS(y, x): queue = deque() queue.append((y, x)) graph[y][x] = 0 count = 1 while queue: y, x = queue.popleft() for i in range(4): nx = x +..
1246 온라인 판매 / 그리디 정답i번째 고객은 pi에 해당하는 수의 이하의 가격만 살 수 있음N = 5 (달걀 수)고객들이 제시한 가격 P = [2, 8, 10, 7] A=7로 정하면 7 이상 지불 가능한 고객은: 7, 8, 10 → 총 3명수익 = 7원 × 3개 = 21원하지만 총 달걀의 수를 초과해서 구매할 수 없기 때문에 min함수를 사용하여 고객과 달걀의 수 중에서 최소값을 고른다n, m = map(int, input().split()) # 달걀의 개수, 손님의 수consumer = [] # 각 손님별로 구매할 수 있는 가격의 최대값for _ in range(m): price = int(input()) consumer.append(price)consumer.sort()idx = 0ans_price = 0ans_eg..
1302 베스트 셀러 / 해시맵 파이썬 자료구조 딕셔너리(dictionary)key-value 쌍으로 데이터를 저장하는 자료구조map이라고 생각하면 됨person = {"name": "Alice", "age": 25}book = {} -> 이런 식으로 선언하면 됨dict.get(key)key 없을 때 에러 대신 None 반환dict.keys()모든 키 반환dict.values()모든 값 반환dict.items()(key, value) 쌍 튜플로 반환dict.pop(key)해당 키 제거 + 값 반환dict.clear()전체 비우기 특정 키가 존재하는지 확인하는 방법person = {"name": "Alice", "age": 25}print("name" in person) # ✅ Trueprint("gender" in person) #..
1697 숨바꼭질 / DFS, BFS 정답일자로 이어진 그래프에서 최단 경로를 찾는다고 생각하면 됨 최단 경로 == BFSfrom collections import dequen, k = map(int, input().split())def BFS(n, k): # 최대 점의 길이 + 1 (리스트는 0부터 시작하므로) max_value = 100001 # 방문을 체크할 리스트 visited = [False] * max_value # 최초 시작지점 (수빈이의 위치)부터의 거리를 담는 리스트 distance = [0] * max_value queue = deque() queue.append(n) visited[n] = True while queue: current = queue.pop..
1012 유기농 배추 / DFS, BFS 정답from collections import dequet = int(input())ans = []for i in range(t): m, n, c = map(int, input().split()) # 배추밭 가로길이, 세로길이, 배추가 심어져 있는 개수 # 배추밭 세팅 graph = [] for _ in range(n): row = [0] * m graph.append(row) for _ in range(c): x, y = map(int, input().split()) graph[y][x] = 1 # 상하좌우 세팅 dx = [-1, 1, 0, 0] dy = [0, 0, -1, 1] def BFS(y, x):..
2468 안전 영역 / DFS, BFS 정답그래프 깊은 복사g = [row[:] for row in graph] 아무런 땅이 물에 젖지 않는 경우도 포함해야 하기 때문에 비가 오는 경우를 0부터 넣어서 체크해야 함 (1부터 시작하면 1이하의 땅은 젖기 때문에)from collections import dequen = int(input()) # n * n 지도# 지도 세팅graph = []for _ in range(n): row = input() row_list = list(map(int, row.split())) graph.append(row_list)# 상하좌우 세팅dx = [-1, 1, 0, 0]dy = [0, 0, -1, 1]def BFS(x, y, g): queue = deque() queue.append((..