Skip to content

Conversation

@zaqquum
Copy link
Collaborator

@zaqquum zaqquum commented May 31, 2025

🌱WIL

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

  • 정말 오랜만에 문제 할당량을 채운 것 같다. 이제 슬슬 인턴 지원으로 노선을 바꿨기 때문에 다시 알고리즘 공부할 때가 된 것 같다. 하반기 및 인턴 대비해서 이번 다가오는 6월 안에 꼭 프로그래머스 lv2 에서 벗어나도록 하자

🚀주간 목표 문제 수: 4개

푼 문제


백준 #11559. 뿌요뿌요: 그래프 / 골드4

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

🚩플로우 (선택)

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

  1. 해당 turn에서 전체 field 속 뿌요뿌요가 있는 위치 확인

    1-2) BFS로 같은 색상의 뿌요가 4개 이상 연결되있는지 확인하기

    -BFS로 연결 개수 확인

    -만약, 4개 이상이면 field 에서 비우고(.) , 변환 flag 을 True 변환

    1-3) 전체 field 돌고 나서 flag = True (한 번이라도 터지면 )이면
    ⇒ 전체 field 돌면서 공중에 떠있는 뿌요뿌요 내리기(함수 refine_field)
    flag = False 이면 → 종료

🚩제출한 코드

import sys
from collections import deque
input = sys.stdin.readline
#1. field 현황 리스트에 담기
# field = [[0]* 6 for _ in range(len(12))]
field = [list(input())[:-1] for _ in range(12)]

#2. bfs
dy = [-1,1,0,0]
dx =[0,0,-1,1]


def refine_field(x) : # 중간 빈자리
  stack = deque()
  #1.아레=> 위로 스택에 뿌요뿌요 순서대로 축척하기 
  for ny in range(11, -1,-1):
    if field[ny][x] != ".":
      stack.append(field[ny][x])
  for ny in range(11, -1, -1) :
    if stack : 
       field[ny][x] = stack.popleft()
    else :
      field[ny][x] = "."

# 연쇄 확인 및 터짐
def bfs(sy,sx):
  q = deque()
  q.append([sy,sx])
  pop_positions = [[sy,sx]]
  cur_color = field[sy][sx]
  visited.append([sy,sx])
  while q : 
    cy,cx = q.popleft()
    for d in range(4):
      ny ,nx = cy + dy[d] ,cx + dx[d]
      # 같은 색상 -> 삭제 등록하기
      if 0<= ny<12 and 0<= nx < 6 and [ny,nx] not in visited  and field[ny][nx] == cur_color :
        q.append([ny,nx])
        pop_positions.append([ny,nx])
        visited.append([ny,nx])
  
  #2) 터짐 확인
  if len(pop_positions) >= 4 :
    for y,x in pop_positions : 
      field[y][x] = "."
    return True
  return False# 안 터짐

answer = 0 
flag = True
k = 0 
while flag  :
  visited = []
  flag =False
  #1. 전체 field에서 뿌요뿌요 탐색
  for i in range(12):
    for j in range(6):
      if field[i][j]!="." and [i,j] not in visited:
        now_f = bfs(i,j) # 2.해당 위치에서 터짐 여부 확인
        flag = flag or now_f
  #2. 연쇄 계수 추가
  if not flag : # False - 안터짐
    break
  else :
    for row in range(6):
        refine_field(row)
  # 현재 turn 에서 1번 이상 터짐
  answer += 1
print(answer)

백준 #11559. 장군: 그래프 / 골드4

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

🚩플로우 (선택)

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

  1. 상& 왕(실제 좌표 위치로 변환) 위치 좌표 + field 값
  2. 이동 가능한 상황_ 3점 모두 비어져있으면 이동 가능
    3점 check 하기 (1) 상하좌우 / (2)대각선 1회 / (2)대각선 2회
    상 - 우상 , 좌상
    하 - 좌하 , 우하
    좌 - 좌상, 좌하
    우 - 우상, 우하

1st erro

  • ny1, nx1 = cy +dy[i%2] , cx+dx[i%2]
    ny2, nx2 = ny1 + dl[dl_combined[i]][0] , nx1 + dl[dl_combined[i]][1]
    ny3 , nx3 = ny2 + dl[dl_combined[i]][0] , nx2 + dl[dl_combined[i]][1]

=> i는 0~8 번으로 상 + 우상/좌상 // 하 + 좌하/우하 // 좌 + 좌상,좌하 // 우 + 우상, 우하 순으로 진행

🚩제출한 코드

import sys
from collections import deque
INF = 1e9
# 상하좌우
dy = [-1,1,0,0]
dx = [0,0,-1,1]

dl= [[-1,1],[1,1],[1,-1],[-1,-1]] # 우상 . 우하 / 좌하 / 좌상
dl_combined = [0,3,1,2,2,3,0,1]
sy ,sx= map(int,sys.stdin.readline().split())
ty,tx = map(int, sys.stdin.readline().split())

field = [[INF]*9 for _ in range(10)]
field[sy][sx] = 0 
field[ty][tx] = -1

q = deque()
q.append([sy,sx])

def check_bound(y,x) :
  if 0<= y <=9 and 0<= x <=8 and field[y][x]!=-1 : # 기물 x , field 안에 , 방문 상관x => 왕 위치만 안됨x
    return True
  return False
def check_bound2(y,x) :
  if 0<= y <=9 and 0<= x <=8 : # 기물 가능
    return True
  return False

while q : 
  cy,cx = q.popleft()
  for i in range(8):
    ny1, nx1 = cy +dy[i//2] , cx+dx[i//2]
    ny2, nx2 = ny1 + dl[dl_combined[i]][0] , nx1 + dl[dl_combined[i]][1] 
    ny3 , nx3 = ny2 + dl[dl_combined[i]][0] , nx2 + dl[dl_combined[i]][1]
    
    if check_bound(ny1, nx1) and check_bound(ny2, nx2) and check_bound2(ny3, nx3) : 
      if ny3 == ty and nx3 == tx : 
        # print(f"succes====")
        print(field[cy][cx] +1)
        
        exit()
      elif field[cy][cx] +1 <= field[ny3][nx3] : 
        field[ny3][nx3] =field[cy][cx] +1 # 업데이트 
        # print(f"{cy}{cx} -> {i}: {ny1}{nx1} / {ny2}{nx2} / {ny3}, {nx3} => field{field[ny3][nx3]} ")
       
        q.append([ny3,nx3])
        # print(f"{cy}{cx} -> {i}: {ny1}{nx2} / {ny2}{nx2} / {ny3}, {nx3} => field{field[ny3][nx3]} ")
  
print(field[ty][tx])

백준 #11559. 토마토: 그래프 / 골드4

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

🚩플로우 (선택)

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

  1. BFS준비 단계 : 익은 토마토 위치(=field[][] = 1)인 위치에서 부터 시작
  2. 안 익은 토마토 확산 시키기 by bfs
    • field의 값 업데이트 - 토마토가 익은 시간
  3. 출력
    1. 다 익음 : field 값 중 최대값 = 마지막에 익은 토마토
    2. 남음 : field 값 중 안 익은(0) 토마토 존재함

🚩제출한 코드

import sys
from collections import deque
#[0] 입력 변수 
input = sys.stdin.readline
N,M = map(int, input().split())
field = [list(map(int,input().split())) for _ in range(M) ]
dy = [-1,1,0,0]
dx = [-0,0,-1,1]

# [1] BFS 초기값 -초기 field에 서 익은 토마토 위치 q에 넣기
q = deque()
for m in range(M) :
        for n in range(N) :
            # print(m , n)
            if field[m][n] == 1: 
                # 안 익은 토마토 익히기 
                q.append([m,n])
                
while q :
    #[2] 익은 토마토 확산시키기
    y,x = q.popleft()
    for d in range(4):
        ny = y + dy[d] ; nx = x + dx[d]
        if 0<= ny <M and 0 <= nx < N and field[ny][nx] == 0:
            # 토마토가 익은 시간때를 filed 값으로 표기
            field[ny][nx] = field[y][x] +1 
            q.append([ny,nx])

#[3] 출력 형태 지정 
# 실패한 경우 : field에 안 익은 토마토(=0) 이 남은 경우
# 성공한 경우 : 다 익은 최소 시간 ==  field에 있는 값(: 익은 시간때) 중 최대값 -1         
max_num = 0 
for i in range(M) :
    for j in range(N):
        if field[i][j]== 0 : 
            print(-1)
            exit()
        max_num = max(max_num , field[i][j])
print(max_num-1)

프로그래머스 #12914.멀리뛰기: Backtracking / lv2

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

🚩제출한 코드

nswer = 0
def solution(n):
    
    def backtracking(path,lv):
        # 재귀 종료
        global answer
        if lv >= len(path):
            if sum(path)==n : 
                answer += 1 
            # print(f"{lv} : {path} >{answer}")
            return 0
        #자식 노드 이동 
        for x in [1,2] :
            if sum(path) + x <= n : 
                path[lv] = x 
                backtracking(path , lv+1)
            # backtracking
            path[lv] = 0 
            
    for m in range(1,n+1) :
        backtracking([0]*m , 0)
    return answer%1234567

Comment on lines +48 to +49
Copy link
Collaborator

Choose a reason for hiding this comment

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

이 부분은 queue=deque([[sy, sx])로 줄일 수 있을 것 같아요!

Comment on lines +34 to +44
Copy link
Collaborator

Choose a reason for hiding this comment

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

저는 위에서 아래로 내리는 코드가 아래 첨부한 코드처럼 3중 반복문을 도는데, 홍주님 코드처럼 stack을 사용하게 되면 O(N)으로 할 수 있군요!! 감사합니다!!

def down():
    for y in range(FIELD_Y):
        for x in range(10, -1, -1):
            for k in range(FIELD_X - 1, x, -1):
                if field[x][y] != '.' and field[k][y] == '.':
                    field[k][y] = field[x][y]
                    field[x][y] = '.'

Comment on lines +1 to +7
Copy link
Collaborator

Choose a reason for hiding this comment

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

토마토 문제는 지난 주에 제가 발제했던 문제였는데, 로직을 잘 구현하셨네요!!
정답 풀이는 아래 발제 자료를 참고해주시면 되겠습니당!
바로가기

Comment on lines +6 to +10
Copy link
Collaborator

Choose a reason for hiding this comment

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

장군 문제는 8가지의 이동 경로를 어떻게 처리하느냐가 관건이었던 것 같아요! 그만큼 발제자님, 저, 홍주님의 경로 표현 방식이 다 다른 게 인상적이네요

저는 아래와 같이 표현했어요!

# 8가지 이동 경로
directions = [
    # 상
    ((-1, 0), (-1, 1), (-1, 1)),    # 오른쪽 위
    ((-1, 0), (-1, -1), (-1, -1)),  # 왼쪽 위
    # 하
    ((1, 0), (1, 1), (1, 1)),       # 오른쪽 아래
    ((1, 0), (1, -1), (1, -1)),     # 왼쪽 아래
    # 좌
    ((0, -1), (-1, -1), (-1, -1)),  # 왼쪽 위
    ((0, -1), (1, -1), (1, -1)),    # 왼쪽 아래
    # 우
    ((0, 1), (-1, 1), (-1, 1)),     # 오른쪽 위
    ((0, 1), (1, 1), (1, 1))        # 오른쪽 아래
]

@Mingguriguri Mingguriguri merged commit 79fa57a into main Jun 7, 2025
@github-actions
Copy link

github-actions bot commented Jun 7, 2025

🔥2025-05 챌린지 진행 상황

👉 그래프

  • zaqquum: 1개 ❌

👉 구현

  • zaqquum: 0개 ❌

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.

3 participants