Skip to content

Conversation

@YoonYn9915
Copy link
Member

@YoonYn9915 YoonYn9915 commented Apr 5, 2025

🌱WIL

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

  • 이번주는 지난 주에 풀지 못한 발제 문제와 과제 문제를 풀었다. 3문제가 다 BFS/DFS유형인데 다 시간 안에 잘 푼것 같다. 적록색약 문제는 지난 7월에 푼 이후 몇 개월만에 다시 풀어봤는데 풀어본 문제답게 대부분 기억이 나서 어려움이 없었다.

🚀주간 목표 문제 수: 3개


백준 #10026. 적록색약: 그래프, BFS, DFS / 골드 5

정리한 링크: (https://purple-jury-c2d.notion.site/8c6528b075434791a09bed32a0e35e32?pvs=4)

🚩제출한 코드

from collections import deque

dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]


def bfs(graph, visited):
    border = 0
    queue = deque()

    # 영역 개수 계산
    for i in range(1, N + 1):
        for j in range(1, N + 1):
            # 현재 칸을 아직 방문하지 않았다면 현재 칸부터 bfs 탐색 시작
            if visited[i][j] == 0:
                # 영역 개수 한 개 증가
                border += 1
                queue.append((i, j))

                while queue:
                    (x, y) = queue.popleft()
                    # 방문처리
                    visited[x][y] = 1

                    # 상하좌우 인접한 칸으로 이동
                    for k in range(4):
                        nx = x + dx[k]
                        ny = y + dy[k]

                        # 칸이 보드 밖으로 넘어가지 않았는지,인접한 칸이 같은 색인지,아직 방문하지 않았는지 확인
                        if (1 <= nx <= N and 1 <= ny <= N) and graph[x][y] == graph[nx][ny] and visited[nx][ny] == 0:
                            # 해당 칸 방문처리
                            queue.append((nx, ny))
                            visited[nx][ny] = 1

    return border


# 입력받기
N = int(input())
graph = [[0] * (N + 1)]
visited = [[0] * (N + 1) for _ in range(N + 1)]

for _ in range(N):
    graph.append([0] + list(input()))

# 정상인이 보는 영역 개수 반환
num_of_normal = bfs(graph, visited)

# 적록색약이 보는 영역 개수 반환 적록색약은 R,G를 구분하지 못하므로 모든 R을 G로 변환
for i in range(1, N + 1):
    for j in range(1, N + 1):
        if graph[i][j] == 'R':
            graph[i][j] = 'G'

visited = [[0] * (N + 1) for _ in range(N + 1)]
num_of_abnormal = bfs(graph, visited)

print(f"{num_of_normal} {num_of_abnormal}")

💡TIL

배운 점이 있다면 입력해주세요


백준 #27737. 버섯 농장: 그래프, BFS, DFS / 실버 1

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

🚩제출한 코드

from collections import deque


def bfs(i, j, visited):
    dx = [-1, 1, 0, 0]
    dy = [0, 0, -1, 1]

    queue = deque()

    # 시작점 방문처리
    queue.append((i, j))
    visited[i][j] = 1

    # 시작점(x,y)으로부터 인접한 버섯 농사 가능 칸의 개수 (시작점 포함)
    num = 1

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

        # 상하좌우 인접한 칸에 버섯 농사 가능한지 보기
        for k in range(4):
            nx = x + dx[k]
            ny = y + dy[k]

            # 그래프 범위에 있는지, 버섯 농사가 가능한지, 아직 방문하지 않았는지 확인
            if (0 <= nx <= N - 1 and 0 <= ny <= N - 1) and graph[nx][ny] == 0 and visited[nx][ny] == 0:
                # 방문처리
                queue.append((nx, ny))
                visited[nx][ny] = 1
                # 버섯 농사 가능한 칸의 개수 증가
                num += 1

    # 해당 구역에 필요한 버섯 포자 개수 반환
    if num % K == 0:
        return num // K
    else:
        return (num // K) + 1


# 입력받기
N, M, K = map(int, input().split())

# 나무판 배열
graph = []
# 나무판 방문 배열
visited = [[0] * N for _ in range(N)]

mushroom_count = 0

for _ in range(N):
    graph.append(list(map(int, input().split())))

for i in range(N):
    for j in range(N):
        # 나무판이 버섯을 심을 수 있고, 아직 방문하지 않았으면
        if graph[i][j] == 0 and visited[i][j] == 0:
            mushroom_count += bfs(i, j, visited)

if mushroom_count == 0 or mushroom_count > M:
    print("IMPOSSIBLE")
else:
    print(f"POSSIBLE\n{M - mushroom_count}")

💡TIL

배운 점이 있다면 입력해주세요


프로그래머스 #43163. 단어 변환: 그래프, BFS, DFS / level 3

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

🚩제출한 코드

# 두 단어가 한글자만 다른지 확인하는 함수
def count_same_letter(word1, word2):

    count = 0
    word_length = len(word1)
    # 모든 단어의 길이는 같으므로 단어의 길이만큼 반복문 돌면서 같은 글자 계산
    for i in range(word_length):
        if word1[i] == word2[i]:
            count += 1

    if word_length - 1 == count:
        return True
    else:
        return False



def dfs(begin, target, words, depth):
    global words_num
    global min_value

    # depth가 words의 크기보다 커지면 해당 탐색 종료
    if depth > words_num:
        return

    # begin과 target이 같다면 탐색 종료
    if begin == target:
        # 현재 depth와 최솟값 비교
        min_value = min(min_value, depth)
        return

    copy_words = words[:]

    for i in range(len(words)):
        # 두 단어가 한글자만 다르다면 그 단어로 변환
        if count_same_letter(begin, words[i]):
            # 단어 목록에서 현재 단어 제외하고
            removed_word = copy_words.pop(i)
            # 다음 detph dfs 실행
            dfs(removed_word, target, copy_words, depth + 1)
            # 배열 원복
            copy_words.insert(i, removed_word)




def solution(begin, target, words):

    # target이 words에 없어서 변환할 수 없는 경우
    if target not in words:
        return 0

    # 단어의 개수
    global words_num
    words_num = len(words)

    global min_value
    min_value = 10000

    dfs(begin, target, words, 0)

    return min_value

💡TIL

배운 점이 있다면 입력해주세요

Copy link
Collaborator

@zaqquum zaqquum left a comment

Choose a reason for hiding this comment

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

이번 주도 문제 푸시느라 고생하셨습니다!!

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
Collaborator

Choose a reason for hiding this comment

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

PR에 문제 제목이 '단어변환'이 아닌 '버섯농장' 으로 되어 있습니다.

@YoonYn9915 YoonYn9915 merged commit 67377d5 into AlgorithmStudy-Allumbus:main Apr 7, 2025
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.

2 participants