본문 바로가기

Python50

[프로그래머스] 행렬 테두리 회전하기 / 파이썬 / Python / 2021 Dev-Matching: 웹 백엔드 💡solutions ) 💬 정해진 행렬 범위의 맨 상단 오른쪽(a, b)에서 부터 시작해서 → ↓ ← ↑ 순으로 행렬 테두리를 회전한다. 💬 이전 값을 before에 저장해놓고 인덱스를 이동하며 행렬 테두리 안의 값들을 바꿔준다. 💬 이때 이동할 때마다 min()함수를 이용해서 행렬 테두리에 해당하는 값들 중 최소값을 판별한다. 👨‍💻code ) def solution(rows, columns, queries): arr = [[0]*columns for _ in range(rows)] num = 1 answer = [] for i in range(rows): for j in range(columns): arr[i][j] = num num += 1 for a,b,c,d in queries: before =.. 2021. 10. 2.
[프로그래머스] 거리두기 확인하기 / 파이썬 / Python / 2021카카오 인턴십 코딩테스트 💡solutions ) 💬 대기실의 각 칸을 하나의 정점으로 보고, 응시자들이 있는 정점을 기준으로 bfs 그래프 탐색을 진행함. 💬 각 정점에서 인접하여 연결된 간선들을 탐색하는데 파티션이 있는 경우는 지나가지 못하고, 거리 2이내의 정점들만 살펴보며 다른 응시자의 유무를 확인함. 💬 이때 지나간 정점은 다시 지나가지 않기 위해 visit 배열을 통해 중복을 체크함. 👨‍💻code ) from collections import deque dx, dy = [-1, 1, 0, 0], [0, 0, -1, 1] # 상하좌우 def bfs(place, i, j): visit = [[0]*5 for _ in range(5)] q = deque() q.append((i, j, 0)) visit[i][j] = 1 w.. 2021. 8. 12.
[프로그래머스] 행렬 테두리 회전하기 / 파이썬 / Python 💡solutions ) 💬 단순히 구현하는 시뮬레이션 문제 💬 테두리 영역의 숫자들을 회전시키기 위해 for문에서 인덱스 범위를 잘 구분하는 것이 중요함 💬 Python에선 두 변수를 한번에 swap이 가능하다 -> e.g) a,b = b,a로 a와 b값 교환 가능 👨‍💻code ) def solution(rows, columns, queries): arr = [[0]*columns for _ in range(rows)] cnt = 1 result = [] for i in range(rows): for j in range(columns): arr[i][j] = cnt cnt += 1 for r1, c1, r2, c2 in queries: min_v = 10001 before = arr[r1][c1-1] .. 2021. 8. 8.
[프로그래머스] 배달 / 파이썬 / Python / Dijkstra 💡solutions ) 💬 다익스트라 알고리즘을 사용하여 최단 거리를 구하는 로직 💬 처음 시작하는 노드 1에서의 최단 거리는 0으로 초기화 💬 인접행렬 만들고 -> heappush를 통해 최단 거리 순으로 정렬 -> 최단 거리가 될 때마다 거리를 저장해 놓는 리스트인 dis 업데이트 👨‍💻code ) import heapq def dijkstra(dis, adj): heap = [] heapq.heappush(heap, [0, 1]) while heap: cost, node = heapq.heappop(heap) for c, n in adj[node]: if cost + c < dis[n]: dis[n] = cost + c heapq.heappush(heap, [cost + c, n]) def solu.. 2021. 6. 14.
[백준] 알고스팟 / 1261번 / 파이썬 / Python / Dijkstra 알고리즘 💡solutions ) 💬 단순 다익스트라(Dijkstra) 알고리즘으로 해결한 문제, 해당 문제에서 노드의 비용에 해당하는 것은 벽을 부순 횟수(cnt) 💬 BFS로도 방문 중복으로 하여 해결할 수 있는 문제 🎫code ) import sys import heapq def dijkstra(): heap = [] heapq.heappush(heap, [0, 0, 0]) # 시작점 visit[0][0] = 1 while heap: cnt, x, y = heapq.heappop(heap) # 벽 부순 횟수가 최소인 경우가 나옴 for k in range(4): nx, ny = x + dx[k], y + dy[k] if x == n - 1 and y == m - 1: # 종료조건 print(cnt) break.. 2020. 12. 6.
[백준] 최소비용 구하기 / 1916번 / 파이썬 / python 💡solutions ) 💬 dijkstra(다익스트라) 알고리즘 유형의 기본 문제 🎫code ) import sys import heapq def dijkstra(n, s, e): dist = [INF] * (n + 1) dist[s] = 0 heap = [] heapq.heappush(heap, [0, s]) while heap: cost, node = heapq.heappop(heap) for n, c in adj[node]: c += cost if c < dist[n]: dist[n] = c heapq.heappush(heap, [c, n]) return dist[e] input = sys.stdin.readline n = int(input()) m = int(input()) adj = [[] fo.. 2020. 12. 5.