Skip to content

solve: [W01] SWEA 1767 프로세서 연결하기 - #5

Merged
yeseoLee merged 1 commit into
mainfrom
week01/yeseoLee
Jul 27, 2026
Merged

solve: [W01] SWEA 1767 프로세서 연결하기#5
yeseoLee merged 1 commit into
mainfrom
week01/yeseoLee

Conversation

@yeseoLee

@yeseoLee yeseoLee commented Jul 24, 2026

Copy link
Copy Markdown
Collaborator

📌 이번 PR 내용

✅ 푼 문제 (SWEA)

번호 문제 링크
1767 프로세서 연결하기 https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV4suNtaXFEDFAUf

🧾 5요소 체크리스트

각 풀이에 아래 5요소를 모두 작성했는지 확인합니다.

  • 1. 접근 방법
  • 2. 시간 복잡도
  • 3. 공간 복잡도
  • 4. 핵심 풀이 방법
  • 5. 실제 코드

📋 규칙 체크

  • 파일 위치/이름 규칙 준수 (studies/week-XX/<깃허브ID>/<문제번호>-<문제이름>.md)
  • 커밋 메시지 템플릿 준수
  • 가능하면 문제를 푼 날(월~목)에 맞춰 그날그날 PR 제출 (놓쳤다면 나중에 몰아서 제출해도 OK)
  • 금요일 마감 전 제출 (해당 주 일정 확인)

💬 리뷰어에게

시간초과를 해결하는 것에서 많이 헤맸습니다.

🧠 이번 주 회고 (한 줄)

파이팅!

Summary by CodeRabbit

  • 문서
    • SWEA 1767 ‘프로세서 연결하기’ 문제의 백트래킹 풀이를 정리한 학습 문서가 추가되었습니다.
    • 코어 연결 우선순위와 전선 길이 최소화 기준, 탐색 및 되돌리기 과정을 Python 코드와 함께 설명합니다.
    • 시간·공간 복잡도와 회고 내용을 기록할 수 있는 항목이 포함되었습니다.

@github-actions
github-actions Bot requested a review from Suyoung-Min July 24, 2026 06:55
@coderabbitai

coderabbitai Bot commented Jul 24, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

SWEA 1767 풀이 문서가 추가되었다. 내부 코어를 대상으로 백트래킹을 수행하며, 연결 코어 수를 우선하고 전선 길이를 최소화하는 Python 구현과 회고를 포함한다.

Changes

프로세서 연결하기 풀이

Layer / File(s) Summary
알고리즘 전략과 풀이 기준
studies/week-01/yeseolee/1767-프로세서 연결하기.md
문제 메타데이터, 백트래킹 접근법, 가장자리 코어 제외 규칙, 최적화 기준과 복잡도 작성 항목을 추가했다.
백트래킹 구현과 실행 코드
studies/week-01/yeseolee/1767-프로세서 연결하기.md
코어별 네 방향 경로를 검사하고 보드를 -1로 표시·복원하며, 연결 코어 수와 전선 길이에 따라 결과를 갱신하는 Python 코드와 테스트 케이스 입출력을 추가했다.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed SWEA 1767 프로세서 연결하기 풀이 추가라는 변경 내용을 직접적으로 요약하고 있어 제목으로 적절합니다.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch week01/yeseoLee

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@studies/week-01/yeseolee/1767-프로세서` 연결하기.md:
- Around line 19-25: 코드 블록에 Python 언어 태그가 누락되어 있습니다. 해당 코드 펜스의 시작 부분을
```python으로 변경해 Python 문법 하이라이팅과 MD040 검사를 충족하세요.
- Around line 30-39: backtracking()이 idx 이후 코어를 다시 순회하지 않고 현재 idx의 코어 하나만 처리하도록
수정해 중복 탐색을 제거하고, 연결 4방향과 미연결 1경우만 재귀 호출하게 하세요. 필요하면 cnt + (M - idx) < answer[0]
가지치기를 추가하고, 문서의 시간 복잡도를 M=len(cores) 기준 O(N·5^M), 공간 복잡도를 O(N² + MN + M)으로
갱신하세요.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 403d4e21-1b0b-49c5-876c-c553499e3079

📥 Commits

Reviewing files that changed from the base of the PR and between 5b5591a and 71047c8.

📒 Files selected for processing (1)
  • studies/week-01/yeseolee/1767-프로세서 연결하기.md

Comment on lines +19 to +25
```
# 잘못 작성한 코드
for i in range(1, n):
for j in range(1, n):
if board[i][j] == 1:
cores.append((i, j))
```

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

코드 펜스에 Python 언어 태그를 추가해 주세요.

정적 분석의 MD040 경고처럼 해당 블록은 Python 코드이므로 ```python으로 시작해야 문서 렌더링과 문법 하이라이팅이 일관됩니다.

수정 예시
-```
+```python
 # 잘못 작성한 코드
 for i in range(1, n):
🧰 Tools
🪛 markdownlint-cli2 (0.23.0)

[warning] 19-19: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@studies/week-01/yeseolee/1767-프로세서` 연결하기.md around lines 19 - 25, 코드 블록에
Python 언어 태그가 누락되어 있습니다. 해당 코드 펜스의 시작 부분을 ```python으로 변경해 Python 문법 하이라이팅과 MD040
검사를 충족하세요.

Sources: Path instructions, Linters/SAST tools

Comment on lines +30 to +39
코어 수는 (7 ≤ N ≤ 12)이고, 각 코어는 상/하/좌/우/미포함 5가지 경우의 수를 가진다.
경계에 코어가 없을 경우, 최악의 경우 5^N 이나 그런 케이스에서는 시간 초과가 발생한다.

**O( )** —

## 3. 공간 복잡도
<!-- 예: O(N) — 방문 배열 N개. -->
O(N^2) board 크기 이상을 요구하지 않는다.

**O( )** —

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

복잡도 표기를 실제 구현과 맞추고, 중복 탐색을 제거해야 합니다.

N은 보드 한 변의 크기이고, 후보 코어 수는 M = len(cores)로 분리해서 계산해야 합니다. 현재 backtracking()idx 이후의 모든 코어를 다시 순회하면서 각 코어에 대해 연결 4가지와 미연결 1가지를 재귀 호출합니다. 따라서 호출 수는 최악의 경우 Θ(6^M), 각 방향의 경로 확인이 O(N)이므로 현재 시간 복잡도는 O(N·6^M)입니다. 문서의 O( )5^N 표기는 모두 실제 코드와 맞지 않습니다.

각 재귀 호출에서 코어 하나만 처리하도록 바꾸면 O(N·5^M)이 되고, cnt + (M - idx) < answer[0] 가지치기도 추가할 수 있습니다. 공간 복잡도는 board O(N²), 코어 목록·재귀 스택 O(M), 활성 path 목록 최대 O(MN)을 합쳐 O(N² + MN + M)입니다.

권장 DFS 구조
 def backtracking(idx, cnt, length):
     nonlocal answer
-    if answer[0] < cnt or (answer[0] == cnt and answer[1] > length):
-        answer = [cnt, length]
+    if idx == len(cores):
+        if answer[0] < cnt or (answer[0] == cnt and answer[1] > length):
+            answer = [cnt, length]
+        return
+
+    if cnt + len(cores) - idx < answer[0]:
+        return

-    for i in range(idx, len(cores)):
-        x, y = cores[i]
+    x, y = cores[idx]
+    for d in range(4):
         ...
-        backtracking(i + 1, cnt + 1, length + len(path))
+        backtracking(idx + 1, cnt + 1, length + len(path))
         ...
-    backtracking(i + 1, cnt, length)
+    backtracking(idx + 1, cnt, length)

Also applies to: 63-88

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@studies/week-01/yeseolee/1767-프로세서` 연결하기.md around lines 30 - 39,
backtracking()이 idx 이후 코어를 다시 순회하지 않고 현재 idx의 코어 하나만 처리하도록 수정해 중복 탐색을 제거하고, 연결
4방향과 미연결 1경우만 재귀 호출하게 하세요. 필요하면 cnt + (M - idx) < answer[0] 가지치기를 추가하고, 문서의 시간
복잡도를 M=len(cores) 기준 O(N·5^M), 공간 복잡도를 O(N² + MN + M)으로 갱신하세요.

Source: Path instructions

@Suyoung-Min Suyoung-Min left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

코드리뷰 by Suyoung-Min

def solution 함수로 실제 알고리즘 부분을 분리하여 구조를 이해하기 쉬웠습니다.
짧은 코드지만 가독성이 좋다고 느껴졌습니다.

코드 관련 제안점은 3가지입니다.

1. 가지치기 부재

백트래킹 함수 시작 부분에 정답 갱신 부분만 있고, 가지치기가 부재합니다. 난이도 있는 백트래킹 문제에서는 가지치기가 되지 않으면 시간, 메모리 제한에 걸릴 수 있으므로 가지치기가 필요합니다.

저는 이 문제에서 두 가지 방식으로 가지치기를 했습니다.

  1. 현재 코어와 남은 코어 개수의 합이 현재 정답 코어보다 작을 때
  2. 현재 코어와 남은 코어 개수의 합이 정답 코어와 같을 때 and 현재 전선 길이가 현재 정답 전선 길이보다 길 때

실제 성능 평가는 아래와 같습니다.

  1. 제 코드와의 SWEA 사이트 코드 실행 기록 비교
Image
  1. 제 코드와의 backtrack 함수 호출 횟수 비교 (첫번째 예제 기준)

call_count: 1543
call_count: 61

2. backtrack 함수 내부 for 문으로 코어 순회

for i in range(idx, len(cores)) 에서 다음 인덱스의 코어로 넘어갑니다.
하지만 이 부분은 for문 내부 backtracking( i + 1, ... ) 가 같은 역할을 하여 중복 탐색의 위험성이 보입니다. 아예 구조를 이진 백트래킹으로 고치거나, 반대로 for문 순회만 남기고 내부 backtrack 호출을 제거하는 방식도 좋습니다.

3. 전선 방문 판독에 사용되는 path 리스트

path 리스트 없이도 해당 작업을 진행할 수는 있지만, 제 코드와 비교할 때 가독성이 훨씬 좋다고 느껴집니다. 메모리 제한이 빡빡하지 않으면 저도 이런 방식을 사용해볼까 합니다.

@yeseoLee
yeseoLee merged commit 70d1b6d into main Jul 27, 2026
2 checks passed
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.

2 participants