Skip to content

Conversation

@zaqquum
Copy link
Collaborator

@zaqquum zaqquum commented Jun 21, 2025

🌱WIL

이번 한 주의 소감을 작성해주세요!

  • 2주 동안 밀린 과제 및 발제 문제 풀이를 완료했다. 특히 숨바꼭질 시리즈를 완주하는게 목표였는데 같은 문제이지만 문제 조건이 변형될 수록 BFS 나 다익스트라 등 접근 방법을 다르게 가져가야 한다는 점이 인상적이였다.

🚀주간 목표 문제 수: 4개

푼 문제


백준 #14226. 이모티콘: 그래프/ 골드4

정리한 링크: (바로가기)

🚩플로우 (선택)

코드를 풀이할 때 적었던 플로우가 있나요?

🚩제출한 코드

import sys
from collections import deque
input = sys.stdin.readline

S = int(input())
visited = [[False]*1002 for _ in range(1002)]
visited[1][0] = True# visited [screen 개수][클립보드 개수] 조합 시 방문 여부 T/F

q = deque([[1,0,0]]) # screen 개수
# 3가지 각 종류의 작업 이후 화면 속 & 클립보드 속 이모티콘 개수 
def function(num , screen , backup ):
    if num == 0 : # copy
        return screen , screen
    elif num == 1  : # put
        return screen + backup , backup 
    elif num == 2: # delete
        return screen -1 , backup 
# 2. BFS 작업
while q: 
    cs , cb , ct =q.popleft()
    # 목표 달성시-> 끝내기
    if cs == S : 
        break
    # cb 에 대한
    if cb == 0 : 
        next_f = [0,2]
    else :
        next_f = [0,1,2]

    for d in next_f : 
        ns , nb = function(d , cs , cb )
        nt = ct+1
        #BFS 화면 적합성
        if 1<= ns <=1001 and not visited[ns][nb] : 
            q.append([ns, nb , nt])
            visited[ns][nb] = True

print(ct)

백준 #13549. 숨바꼭질3: 그래프/ 골드5

정리한 링크: (바로가기)

🚩플로우 (선택)

코드를 풀이할 때 적었던 플로우가 있나요?

  1. 입력 변수 입력하기

    1. visited[현 위치] = 도달하는데 걸리는 시간 ( default = MAX)
    2. deque 인 q : 위치 x
  2. BFS 탐색 시 순간이동을 우선순위를 둠

    → for문 탐색시 , 2*n >> n-1, n+1 순으로 탐색

  3. 배열 visited에 도착 시간 업로드

    1. 순간이동 한 경우 → +0초
    2. 걸어온 경우 → +1 초

🚩제출한 코드

import sys
from collections import deque
input = sys.stdin.readline
MAX = 100001
N , K  = map(int,  input().split())
visited = [MAX] * (MAX+1) # 방문 여부
# 2. BFS로 N-> K 의 모든 경로 찾기
q = deque([N])
visited[N]= 0 

while q : 
  cx= q.popleft()
  ct = visited[cx] 
  if cx == K: 
     break
  for nx in (2*cx , cx-1 , cx+1 ) :
    if 0 <= nx < MAX and visited[nx] >= MAX : # nx 의 제한 조건
      # 시간 업데이트 
      if nx == 2*cx : 
          visited[nx] = visited[cx]
      else : 
          visited[nx] = visited[cx] +1
      
      q.append(nx)
print(visited[K])

백준 #12851. 숨바꼭질2: 그래프/ 골드4

정리한 링크: (바로가기)

🚩플로우 (선택)

코드를 풀이할 때 적었던 플로우가 있나요?

🚩제출한 코드

import sys 
from collections import deque
N , K = map(int, sys.stdin.readline().split())
INF = 1000001
field = [[INF,0]]*INF# field[x] = 최단 시간
# BFS 특 : 먼저 방문한 경우가 최단 시간임
q = deque([N])
field[N] = [0,1] # 최단시간 , 경우의 수 

while q : 
   x  = q.popleft() # 현 위치
   ct , cn =field[x] # 현 위치에서 최단 시간 , 경우의 수
#    if field[K][0] < ct : # 종료 조건 : 
#       break 
   for nx in [x-1 , x+1 , 2*x]:
      if 0<= nx < INF:
        #[1] 첫 방문인 경우 : field[nx][1] == 0 -> 최단 시간 업데이트 & q 에 넣기 
        if field[nx][1] == 0 : 
            field[nx] = [ct +1 ,cn]
            q.append(nx) # 위치 업데이트
            # print(f"update {nx} => field[nx] : {field[nx]}")
        #[2] 중복 방문인 경우(최단 시간이 같을때)-> field[x][1]누적 경로의 수 추가
        elif field[nx][0] == ct +1  : 
            field[nx][1] += cn 
            # print(f"## duplicate :{nx} - {field[nx]}")
        # 최단 시간이 더 큼 -> 암 것도 없음

print(field[K][0])
print(field[K][1])

백준 #1697. 숨바꼭질: 그래프/ 실버1

정리한 링크: (바로가기)

🚩플로우 (선택)

코드를 풀이할 때 적었던 플로우가 있나요?

🚩제출한 코드

import sys
from collections import deque
input = sys.stdin.readline
MAX = 100000
# 1. N, K 입력변수 입력 받기
N ,K = map(int, input().split())
# 2. N과 K 가 같을 때 , 예외처리
if N == K : 
  print(0)
  exit()

# 3. BFS 로 K까지 도달하는데 최단 거리 출력하기
q = deque([N])
visited = [False] * (MAX + 1)
visited[N] = True
lv = 1 
#[1] while 을 최단거리(level) 만큼 반복
while q:
  level_size = len(q) 
  next_lv = []
  #[2] 현 lv 의 노드만 BFS 탐색 & 다음 lv 후보군 노드을 enqueue
  for _ in range(level_size) :
    cx = q.popleft()
    for nx in (cx-1 , cx+1 ,2*cx) : 
      if 0 <= nx <= MAX:
        if nx == K :  # 목적지 도착
          print(lv)
          exit()
        # 첫 방문 
        if not visited[nx] : 
          q.append(nx)
          next_lv.append(nx)
  # print(f"##{lv}= {level_size} => {next_lv}")
  lv +=1
  for x in next_lv :
    visited[x]

프로그래머스 #17680. 캐시: 구현 / lv2

정리한 링크: (바로가기)

🚩플로우 (선택)

코드를 풀이할 때 적었던 플로우가 있나요?

🚩제출한 코드

def solution(cacheSize, cities):
    answer = 0
    #1. 모든 도시이름 소문자 -> 대문자로 통일
    for c in range(len(cities)): 
        cities[c]=cities[c].upper()
    stack = []
    # +예외처리 : chachSize가 0일때 -> answer = 5*dB개수 
    if cacheSize <= 0 : 
        return (5*len(cities))
    # 2. City 개수만큼 반복
    for i in range(len(cities)):
        city = cities[i]
        cache_miss = True
        # 2-1 . Stack에 있을때(cache hit)
        for s in range(len(stack)):
            if city == stack[s][1] : # stack에 있음
                answer += 1 # cache hit 시간 추가
                cache_miss = False 
                stack[s][0] =  answer # 데이터 사용 시간 업데이트 
                
        #2-2. 위 cache 탐색 후에도 Cache miss 발생
        if cache_miss : # Cache miss 남  
            # [1] cache miss 발생& stack이 not full
            answer += 5 
            if len(stack) < cacheSize:
                stack.append([answer,city])
            #[2] cache miss 발생 & stack 이 full 한 경우 -> replace 교체 (recently cache)
            else :
                # stack내에 검색 시간이 가장 이른 db 버리기 
                stack.sort(key = lambda x : x[0])
                stack.pop(0)
                # 새로운 data로 교체
                stack.append([answer,city])

    return answer

##백준 #13913. 숨바꼭질4: 그래프 / 골드4
정리한 링크: (바로가기)

🚩플로우 (선택)

코드를 풀이할 때 적었던 플로우가 있나요?
[0] 입력 변수 입력하기

  • visited[현재 위치] = [ 도착 시간 t, 출발지 cx]
    • 즉 바로 직전 출발지 → 현재위치 = 도착지을 최단 시간과 같이 1개의 배열 visited 로 관리함
    • 초기값 visied[N] = [0,N]

[1] BFS을 활용해 최단 시간 찾기

  1. 출발지와 도착지(N==K) 가 같은 경우 예외 처리
  2. while 문과 첫번째 for문을 통해, 같은 level(시간 t) 인 경우를 한번에 처리하기
  3. 두번째 for 문으로 BFS 탐색하기

[2] 최단 시간을 가진 “경로” 출력하기

  • visited 내의 출발지 cx 을 통해 최종 도착지 K 로 부터 최초 출발지 N 까지의 경로를 역추적함

    ex) 5 ,17

    visited[17] = [ 4, 18]

    visited[18] = [3, 9]

    visited[9] = [2 , 10]

    visited[10] = [1, 5 ]

    visited[5] = [0,5]

🚩제출한 코드

import sys
from collections import deque
input = sys.stdin.readline
N, K = map(int, input().split())
MAX = 100001
# answer = [] 
#[1] 최단 시간 찾기 
visited = [[MAX, MAX] for _ in range(MAX+1)]# level 기입

t= 0
next_node = [N]
q = deque([N])
visited[N] = [t,N] # 도착 시간 , 이전 node 위치 확인

#(예외처리) 출발지 = 도착지 같은 경우
if K != N : 
  while q :
    t+=1
    next_node = len(q)
    # print(F"t{t}")
    for i in range(next_node) : # 현재 level의 node개수만큼 반복
      cx = q.popleft()
      # print(f"cx {cx} , {next_node}")
      # 만약 목적 달성시 , 끝
      for nx in [cx -1 , cx+1 , cx*2]:
        if 0<= nx <= MAX and visited[nx][0]>= MAX : 
          q.append(nx)
          visited[nx] = [t, cx]   
    # 현재 q -> 다음 level 의 노드만 남아있는 상태
    # 만약 K을 도달한 경우-> 최단 시간 저장
    if visited[K][0]< MAX : 
      break
print(t)
#[2] 역추적 - 최단 시간 경우 , 경로 추적
re_visited = [K]
pt = K
while pt != N : 
  _ , pt =visited[pt]
  re_visited.append(pt)

# print(re_visited)
print(" ".join(map(str,list(reversed(re_visited)))))

프로그래머스 #12911. 다음 큰 숫자: 구현 / lv2

정리한 링크: (바로가기)

🚩플로우 (선택)

코드를 풀이할 때 적었던 플로우가 있나요?

🚩제출한 코드

def solution(n):
    answer= 0
    bin_flag= True
    one = list(str(bin(n))).count("1")
    while bin_flag :
        n+=1
        bin_flag = not(str(bin(n))[2:].count("1") == one)
    answer=n 
        
    
    return answer

Copy link
Collaborator

@Mingguriguri Mingguriguri left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

한 주간 7문제나 풀이하다니! 너무 고생 많으셨어요!!
이번 주 발제 문제의 경우, 저랑 로직이 거의 비슷해서 따로 코드리뷰 남기진 않았습니다!

Important

PS. 숨바꼭질3 파이썬 파일이 올라와있지 않은 것 같아요! 확인 후 Push 해주시면 감사하겠습니당! 그러면 추가로 과제 문제도 코드리뷰 진행할 수 있을 것 같습니다!

스크린샷 2025-06-22 오전 11 26 40

Comment on lines +1 to +16
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

지난 주 풀이도 함께 올려주셨네요! 👍
지난 주 발제자료로 다양한 풀이를 추가해두었는데 참고해주세요!
https://github.com/AlgorithmStudy-Allumbus/codingtest_algorithm_study/blob/main/_WeeklyChallenges/W26-%5BGraph-BFS%5D/Study_BOJ_12851_%EC%88%A8%EB%B0%94%EA%BC%AD%EC%A7%882.py

Comment on lines +21 to +32
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

혹시 여기서 왜 2중 for문을 쓰셨는지 알 수 있을까요???

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member

@YoonYn9915 YoonYn9915 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

전반적으로 발제문제와 과제문제에서 아이디어를 잘 떠올리셨고 로직에 따라 명확한 코드를 작성해주신 것 같습니다!

한 주 수고하셨습니다~

Comment on lines +26 to +40
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

큐에 좌표만 넣고 시간은 visited 배열에 따로 관리하면서 깔끔하고 가독성 좋은 코드가 된것 같습니다. 👍

Comment on lines +11 to +15
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저는 이번 문제에 이 순간이동 관련한 아이디어를 떠올리기가 힘들었는데... 잘 생각해서 정리해주신것 같아요!

@zaqquum zaqquum merged commit 435cc6f into main Jun 23, 2025
@github-actions
Copy link

🔥2025-06 챌린지 진행 상황

👉 그래프

  • YoonYn9915: 3개 ❌
  • Mingguriguri: 4개 ❌
  • zaqquum: 5개 ✅

👉 구현

  • YoonYn9915: 1개 ❌
  • Mingguriguri: 1개 ❌
  • zaqquum: 2개 ❌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants