정답

  • 나이트가 이동할 수 있는 경우의 수를 처음에 아래와 같이 했더니 오답이 나옴
    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 deque
case = int(input())
ans = []
for _ in range(case):
    n = int(input())
    graph = []
    for _ in range(n):
        row = [0] * n
        graph.append(row)

    distance = []
    for _ in range(n):
        row = [0] * n
        distance.append(row)

    start_x, start_y = map(int, input().split())
    goal_x, goal_y = map(int, input().split())

    # 시계방향대로 이동 할 수 있는 수를 둠, BFS에서는 방향 순서를 신경써야 함
    dx = [-2, -1, 1, 2, 2, 1, -1, -2]
    dy = [1, 2, 2, 1, -1, -2, -2, -1]

    def BFS(y, x):
        queue = deque()
        queue.append((y, x))
        graph[y][x] = 1

        while queue:
            y, x = queue.popleft()

            if y == goal_y and x == goal_x:
                return distance[y][x]

            for i in range(len(dx)):
                nx = x + dx[i]
                ny = y + dy[i]

                if 0 <= nx < n and 0 <= ny < n and graph[ny][nx] == 0:
                    distance[ny][nx] = distance[y][x] + 1
                    queue.append((ny, nx))
                    graph[ny][nx] = 1

    ans.append(BFS(start_y, start_x))

for i in ans:
    print(i)

'Algorithm' 카테고리의 다른 글

5014 스타트링크 / DFS, BFS  (0) 2025.05.28
1926 그림 / DFS, BFS  (0) 2025.05.27
1246 온라인 판매 / 그리디  (0) 2025.05.26
1302 베스트 셀러 / 해시맵  (0) 2025.05.25
1697 숨바꼭질 / DFS, BFS  (0) 2025.05.24

 

정답

  • 숨바꼭질이랑 비슷한 문제
  • 하나의 그래프에서 최소거리로 탐색한다고 보면 됨
from collections import deque
f, 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 in (current + u, current - d):
            if 0 < next <= f and not visited[next]:
                queue.append(next)
                visited[next] = True
                distance[next] = distance[current] + 1

    return "use the stairs"

print(BFS(s))

'Algorithm' 카테고리의 다른 글

7562 나이트의 이동 / DFS, BFS  (0) 2025.05.29
1926 그림 / DFS, BFS  (0) 2025.05.27
1246 온라인 판매 / 그리디  (0) 2025.05.26
1302 베스트 셀러 / 해시맵  (0) 2025.05.25
1697 숨바꼭질 / DFS, BFS  (0) 2025.05.24

정답

from collections import deque
n, 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 + dx[i]
            ny = y + dy[i]

            if nx < 0 or ny < 0 or nx >= m or ny >= n:
                continue

            if graph[ny][nx] == 0:
                continue

            if graph[ny][nx] == 1:
                queue.append((ny, nx))
                graph[ny][nx] = 0
                count = count + 1


    return count

ans = []
art = 0
for y in range(n):
    for x in range(m):
        if graph[y][x] == 1:
            art = art + 1
            ans.append(BFS(y, x))


print(art)
if art == 0:
    print(0)
else:
    print(max(ans))

 

 

 

'Algorithm' 카테고리의 다른 글

7562 나이트의 이동 / DFS, BFS  (0) 2025.05.29
5014 스타트링크 / DFS, BFS  (0) 2025.05.28
1246 온라인 판매 / 그리디  (0) 2025.05.26
1302 베스트 셀러 / 해시맵  (0) 2025.05.25
1697 숨바꼭질 / DFS, BFS  (0) 2025.05.24

 

정답

  • 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 = 0
ans_price = 0
ans_egg_price = 0
for p in consumer:
    count = min(n, len(consumer[idx:]))
    idx = idx + 1
    max_price = count * p
    if ans_price < max_price:
        ans_price = max_price
        ans_egg_price = p

print(ans_egg_price, ans_price)

'Algorithm' 카테고리의 다른 글

5014 스타트링크 / DFS, BFS  (0) 2025.05.28
1926 그림 / DFS, BFS  (0) 2025.05.27
1302 베스트 셀러 / 해시맵  (0) 2025.05.25
1697 숨바꼭질 / DFS, BFS  (0) 2025.05.24
1012 유기농 배추 / DFS, BFS  (0) 2025.05.23

 

 

파이썬 자료구조 딕셔너리(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)   # ✅ True
print("gender" in person) # ❌ False

 

정답

  • 알파벳도 sort(), sorted() 함수로 오름차순, 내림차순 정렬이 가능함
n = int(input())
book = {}

for _ in range(n):
    title = input()

    # 이미 딕셔너리에 값이 있다면 1 증가, 아니라면 값 1 넣기
    if title in book:
        book[title] = book[title] + 1
    else:
        book[title] = 1

# 딕셔너리의 값들 중, 가장 큰 수 추출
best = max(book.values())

ans = []
# 딕셔너리를 탐색하며 가장 큰 수와 같은 값을 가진 책 이름 리스트에 추가
for key, value in book.items():
    if value == best:
        ans.append(key)
# 오름차순으로 알파벳 정렬
a = sorted(ans)
print(a[0])

'Algorithm' 카테고리의 다른 글

1926 그림 / DFS, BFS  (0) 2025.05.27
1246 온라인 판매 / 그리디  (0) 2025.05.26
1697 숨바꼭질 / DFS, BFS  (0) 2025.05.24
1012 유기농 배추 / DFS, BFS  (0) 2025.05.23
2468 안전 영역 / DFS, BFS  (1) 2025.05.22

 

정답

  • 일자로 이어진 그래프에서 최단 경로를 찾는다고 생각하면 됨 
  • 최단 경로 == BFS
from collections import deque
n, 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.popleft()

        # 현재 위치가 동생의 지점이라면, 수빈이의 지점부터 동생의 지점까지의 거리 반환
        if current == k:
            return distance[current]

        # 현재 위치가 동생의 지점이 아니라면, 수빈이가 갈 수 있는 경우의 수 걷기, 뛰기를 적용하여 조건에 부합한다면 큐에 넣기
        for next in (current - 1, current + 1, current * 2):
            # 0이상, 100000이하이고 방문하지 않았다면
            if next >= 0 and next < max_value and not visited[next]:
                queue.append(next)
                visited[next] = True
                distance[next] = distance[current] + 1

print(BFS(n, k))

'Algorithm' 카테고리의 다른 글

1246 온라인 판매 / 그리디  (0) 2025.05.26
1302 베스트 셀러 / 해시맵  (0) 2025.05.25
1012 유기농 배추 / DFS, BFS  (0) 2025.05.23
2468 안전 영역 / DFS, BFS  (1) 2025.05.22
2583 영역 구하기 / DFS, BFS  (0) 2025.05.21

 

정답

from collections import deque
t = 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):
        queue = deque()
        queue.append((y, x))
        graph[y][x] = 0

        while queue:
            y, x = queue.popleft()
            for i in range(4):
                nx = x + dx[i]
                ny = y + dy[i]

                if nx < 0 or ny < 0 or nx >= m or ny >= n:
                    continue

                if graph[ny][nx] == 0:
                    continue

                if graph[ny][nx] == 1:
                    queue.append((ny, nx))
                    graph[ny][nx] = 0



    count = 0
    for y in range(n):
        for x in range(m):
            if graph[y][x] == 1:
                count = count + 1
                BFS(y, x)

    ans.append(count)

for i in ans:
    print(i)

'Algorithm' 카테고리의 다른 글

1302 베스트 셀러 / 해시맵  (0) 2025.05.25
1697 숨바꼭질 / DFS, BFS  (0) 2025.05.24
2468 안전 영역 / DFS, BFS  (1) 2025.05.22
2583 영역 구하기 / DFS, BFS  (0) 2025.05.21
2667 단지번호붙이기 / DFS, BFS  (0) 2025.05.20

 

정답

  • 그래프 깊은 복사
g = [row[:] for row in graph]

 

  • 아무런 땅이 물에 젖지 않는 경우도 포함해야 하기 때문에 비가 오는 경우를 0부터 넣어서 체크해야 함 (1부터 시작하면 1이하의 땅은 젖기 때문에)
from collections import deque
n = 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((x, y))
    g[x][y] = 0

    while queue:
        x, y = queue.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]

            if nx < 0 or ny < 0 or nx >= n or ny >= n:
                continue
            if g[nx][ny] == 0:
                continue
            if g[nx][ny] != 0:
                queue.append((nx, ny))
                g[nx][ny] = 0

# 0부터 100까지 높이로 물에 잠긴다고 가정했을 때 뮬애 안 잠기는 가장 큰 수가 정답 (아무 지역도 물에 안 잠기는 경우도 있으므로 0부터 시작해야 함)
ans = []
for i in range(0, 101):
    area = 0
    # 그래프 세팅
    g = [row[:] for row in graph]
    for x in range(n):
        for y in range(n):
            if g[x][y] <= i:
                g[x][y] = 0

    for x in range(n):
        for y in range(n):
            if g[x][y] != 0:
                area = area + 1
                BFS(x, y, g)

    ans.append(area)

print(max(ans))

'Algorithm' 카테고리의 다른 글

1697 숨바꼭질 / DFS, BFS  (0) 2025.05.24
1012 유기농 배추 / DFS, BFS  (0) 2025.05.23
2583 영역 구하기 / DFS, BFS  (0) 2025.05.21
2667 단지번호붙이기 / DFS, BFS  (0) 2025.05.20
2178 미로 탐색 / DFS, BFS  (0) 2025.05.19

+ Recent posts