Skip to content

Conversation

@Monixc
Copy link
Contributor

@Monixc Monixc commented Oct 30, 2025

No description provided.

Copy link
Contributor

@Dianuma Dianuma 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
Contributor

Choose a reason for hiding this comment

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

이 풀이는 코딩 테스트 환경이라 n 이 잘못된 값으로 들어올 가능성은 거의 없지만,
일반적인 상황에서는 cost[n-1][n-1] 보다 cost[-1][-1]처럼 음수 인덱스를 사용하는 편이 더 안전합니다.
리스트 크기가 달라지더라도 항상 마지막 원소를 참조할 수 있기 때문입니다.

3차원 cost 배열을 사용해 방향별 최소비용 DP를 구현한 점이 인상적입니다.
또, 코드가 문제를 처음 접하는 사람도 구조를 바로 이해할 수 있을 정도로 친절한 구현이라고 생각합니다.

Copy link
Contributor

Choose a reason for hiding this comment

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

정석적인 DFS 풀이입니다.
로직이 깔끔하고 효율적이며, 가독성까지 좋은 아주 좋은 코드라고 생각합니다.

def solution(n, computers):
    visited = [0] * n
    def dfs(i):
        visited[i] = 1
        for j, computer in enumerate(computers[i]):
            if computer and not visited[j]: dfs(j)
    return sum([not v and not dfs(i) for i, v in enumerate(visited)])

황다경 님의 코드를 참고해서 제 스타일대로 조금 변형해봤습니다.
파이썬은 True1 로 취급하므로 조건문을 간소화했고,
sum()iterator 를 받을 수 있다는 점을 활용해 return문을 한 줄로 압축했습니다.
개인적으로는 코테에서는 가독성을 약간 희생하더라도 간결하게 표현하는 코드 스타일을 선호하기 때문에,
7줄로 완성된 이 버전이 제가 원래 작성한 코드보다 마음에 듭니다.

물론, 실제 협업할 동료를 고른다면 황다경 님처럼 의도가 명확히 드러나는 가독성 높은 코드를 짜는 분을 선택할 것 같긴 하지만요.

Copy link
Contributor

Choose a reason for hiding this comment

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

황다경님이 작성하신 코드는 로직이 명확해서 읽기 매우 편합니다.

다만 저는 코딩 테스트를 할 때 가독성보다 최대한 짧은 코드를 선호하는 편이라,
아래 예시는 “이런 식으로도 표현할 수 있구나” 정도로 가볍게 봐주시면 좋겠습니다.
실제 협업이나 실무 상황에서는 황다경님처럼 가독성을 중시하는 스타일이 훨씬 좋다고 생각합니다.

nc = c + 100 + 500 * ( i != dir_prev );

저는 파이썬이 True1 로 취급한다는 점을 이용해서 위와 같이 코드를 작성했습니다.
가독성을 좀 더 높이려면 아래처럼 삼항연산자를 이용해도 좀 더 파이써닉한 코드가 될 것 같습니다.

nc = c + (100 if d == prev else 600)

그리고 nc 계산을 밖으로 빼면

while q:
        x, y, dir_prev, c = q.popleft()
        nc = c + 100 + 500 * ( i != dir_prev );
        if 0 <= nx < n and 0 <= ny < n and board[nx][ny] == 0 and nc < cost[nx][ny][i:
               cost[nx][ny][i] = nc
               q.append((nx, ny, i, nc))

이런 식으로 조건문을 압축 할 수 있습니다.

Copy link
Contributor

Choose a reason for hiding this comment

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

이 코드도 정석적인 DFS 풀이라고 생각됩니다. 마찬가지로 로직이 깔끔하고 읽기에도 매우 편합니다.

사견을 덧붙이자면, visited 를 처음부터 True 로 초기화하고 방문 시 False 로 바꾸는 방식도 있습니다.
이렇게 하면 조건문에서 not 을 사용하지 않아도 되어, 조금 더 단순한 형태로 표현할 수 있습니다.
다만 이는 코딩 스타일의 차이로, visited 라는 변수명을 생각하면 오히려 원본 방식이 더 자연스러운 구현이라고는 생각합니다.

Copy link
Contributor

Choose a reason for hiding this comment

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

파이썬의 문자열은 인덱싱이 가능하며 불변(immutable) 객체이기 때문에, 수정이 필요한 경우에만 리스트로 변환하는 것이 의미 있습니다.
이 코드에서는 maps 를 변경하지 않으므로 해당 변환은 불필요해 보입니다.

Copy link
Contributor

Choose a reason for hiding this comment

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

to_leverto_exit 를 분리해, 둘 중 하나라도 경로 탐색에 실패하면 바로 종료하도록 한 구조가 인상적입니다.
불필요한 BFS 호출을 줄여 효율적인 흐름 제어가 잘 되어 있다고 느꼈습니다.

Copy link
Contributor

Choose a reason for hiding this comment

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

graph[key].sort()
graph[key].sort(reverse=True)

두 코드는 정렬 알고리즘이 동일하므로 시간 복잡도는 모두 O(n log n)입니다.
다만 오름차순 정렬 시에는 pop(0) 을 사용해야 하는데, 이 연산은 O(n) 시간이 걸립니다.
반면 내림차순 정렬의 경우 pop() 으로 맨 뒤에서 꺼낼 수 있어 O(1)에 처리됩니다.

따라서 이후 데이터를 pop() 으로 순차적으로 꺼내는 로직이라면,
역순 정렬이 전체적으로 더 효율적이라고 생각됩니다.

Copy link
Contributor

Choose a reason for hiding this comment

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

이 문제도 읽기에 매우 편해 좋은 코드라고 생각합니다.

@Monixc Monixc merged commit 7cb9b7d into main Nov 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants