Skip to content

[W01] Suyoung-Min - SWEA 1767번 - #2

Merged
clarityth merged 1 commit into
mainfrom
week01/Suyoung-Min
Jul 27, 2026
Merged

[W01] Suyoung-Min - SWEA 1767번#2
clarityth merged 1 commit into
mainfrom
week01/Suyoung-Min

Conversation

@Suyoung-Min

@Suyoung-Min Suyoung-Min 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)
  • 커밋 메시지 템플릿 준수
  • 금요일 마감 전 제출 (해당 주 일정 확인)

💬 리뷰어에게

  • 전선 탐색하는 while 문이 반복되는데, 적절하게 반복문을 줄이는 방법이 있는지 ( 함수형태로 바꾸기?)
  • 추가할만한 가지치기 방법이 있는지 or 현재 가지치기를 좀 더 효율적인 방법으로 교체할 수 있는지
  • 코드 구조의 가독성이 괜찮은지, 그렇지 않다면 가독성을 어떻게 효율적으로 고칠 수 있는가

🧠 이번 주 회고 (한 줄)

백트래킹 구조 구성에 가지치기의 효율성을 명심하자

Summary by CodeRabbit

  • 문서
    • SWEA 1767 ‘프로세서 연결하기’ 문제의 풀이 기록이 추가되었습니다.
    • 내부 코어를 대상으로 한 백트래킹 접근법과 상·하·좌·우 전선 연결 과정을 설명합니다.
    • 최대 연결 코어 수와 최소 전선 길이를 기준으로 해를 선택하는 방법을 정리했습니다.
    • 가지치기, 격자 마킹 및 복원 방식, 파이썬 구현 예시와 개선 회고를 포함합니다.

@github-actions
github-actions Bot requested a review from clarityth July 24, 2026 00:14
@coderabbitai

coderabbitai Bot commented Jul 24, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

SWEA 1767 풀이 문서가 추가되었다. 내부 코어를 대상으로 전선 연결 여부와 네 방향을 백트래킹으로 탐색하며, 연결 코어 수 최대와 전선 길이 최소를 기준으로 가지치기와 격자 복원을 수행한다.

Changes

프로세서 연결 풀이

Layer / File(s) Summary
탐색 기준과 가지치기 정리
studies/week-01/Suyoung-Min/1767-프로세서연결하기.md
내부 코어를 대상으로 연결 코어 수 최대, 전선 길이 최소의 사전식 최적화 기준과 복잡도, 격자 마킹 및 두 가지 가지치기 조건을 설명한다.
백트래킹 구현과 회고
studies/week-01/Suyoung-Min/1767-프로세서연결하기.md
테스트케이스 처리, 방향별 전선 탐색·마킹·복원, 최적값 갱신, 미연결 선택을 포함한 재귀 구현과 stretch 개선 아이디어를 추가한다.

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

Possibly related PRs

  • DevJunz/coding-test-study-template#1: 동일한 SWEA 1767 문제에 대해 내부 코어 백트래킹, 격자 전선 마킹, 연결 코어 수와 전선 길이 기준을 다룬다.
🚥 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/Suyoung-Min

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: 1

🤖 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/Suyoung-Min/1767-프로세서연결하기.md`:
- Line 91: ASCII 인덱스 다이어그램의 코드 펜스에 text 언어 태그를 추가하세요. 해당 문서의 언어 태그가 없는 모든 펜스를
```text로 변경해 Markdown lint 경고 MD040을 해결하고, 다이어그램 내용은 그대로 유지하세요.
🪄 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: 1de2ea0d-f102-4688-8d58-d20b2fad43eb

📥 Commits

Reviewing files that changed from the base of the PR and between 5b5591a and 019d0c8.

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

`rest = len(cores) - cidx`이지 `len(cores) - 1 - cidx`가 아니다.
`backtrack(cidx, cnum, ...)` 시점에서 `cnum`은 **인덱스 0 ~ cidx-1**만 센 값이고, `cidx`는 아직 미결정 = **앞으로 연결 가능한 후보**다.

```

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

코드 펜스에 언어 태그를 추가하세요.

ASCII 인덱스 다이어그램이므로 text 태그를 사용하면 Markdown lint 경고(MD040)를 해소할 수 있습니다.

수정 예시
-```
+```text
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
```
🧰 Tools
🪛 markdownlint-cli2 (0.23.0)

[warning] 91-91: 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/Suyoung-Min/1767-프로세서연결하기.md` at line 91, ASCII 인덱스 다이어그램의 코드
펜스에 text 언어 태그를 추가하세요. 해당 문서의 언어 태그가 없는 모든 펜스를 ```text로 변경해 Markdown lint 경고
MD040을 해결하고, 다이어그램 내용은 그대로 유지하세요.

Sources: Path instructions, Linters/SAST tools

@Suyoung-Min Suyoung-Min changed the title solve: [SWEA 1767] 프로세서 연결하기 [W01] Suyoung-Min - SWEA 1767번 Jul 24, 2026

@clarityth clarityth 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.

Code Review by clarityth

좋았던 점:

  1. 2가지 가지치기 조건 도출
  2. 방문 로직 처리를 위한 visited 배열을 별도로 선언하는 것이 아닌 grid에 직접적으로 기록해 공간복잡도를 줄인 점

이미 제가 작성한 코드보다 훨씬 좋은 코드라고 생각하지만, 추가적으로 제가 생각한 개선점은 다음과 같습니다.

1. 경로 검사 로직 플래그 변수 제거

  • 기존 코드 로직에서 무한루프문으로 진행하기 때문에 break 조건이 잘못 설정 됐을 경우의 위험성이 있다고 생각합니다.
  • 따라서 아래와 같이 while문의 조건식을 움직일 수 있는 조건식으로 설정하고, break문을 만나지 않고 정상 종료되었을 때(else 블록) 수행할 작업을 작성하면 가독성 측면에서 더 좋을 것 같습니다.
  • 또한 방문 처리 마킹 작업에서도 앞서 도출한 cur_line_length를 활용해 for문으로 지정된 횟수만큼만 반복하도록 수정하면 좋을 것 같습니다.

기존 코드

cover_flag = False
cur_line_length = 0
ny, nx = cy, cx

while True:
    ny += dy; nx += dx
    if ny < 0 or ny >= n or nx < 0 or nx >= n: break
    if grid[ny][nx] != 0: 
        cover_flag = True
        break
    cur_line_length += 1

if not cover_flag:
    # 방문 처리 및 복원 시 while True와 경계 조건 검사 반복
    ny, nx = cy, cx
    while True:
        ny += dy; nx += dx
        if ny < 0 or ny >= n or nx < 0 or nx >= n: break
        grid[ny][nx] = 2 

개선 코드

cur_line_length = 0
ny, nx = cy, cx

while 0 <= ny + dy < n and 0 <= nx + dx < n:
    ny += dy; nx += dx
    if grid[ny][nx] != 0: 
        break
    cur_line_length += 1
else:
    # 방문 처리 (계산된 길이만큼만 for문 반복)
    ny, nx = cy, cx
    for _ in range(cur_line_length):
        ny += dy; nx += dx
        grid[ny][nx] = 2

2. 가장자리에 위치한 코어 우선 탐색

  • 현재 코드는 좌측 상단부터 우측 하단까지 순회하며 코어의 위치를 기록하고, 그 기록된 순서에 따라 코어들의 연결 여부를 판정하고 있습니다.
  • 가장자리와의 거리를 기준으로 오름차순으로 정렬해 외곽에 위치한 코어를 우선적으로 탐색하면, 이후 가지치기 로직과 시너지를 내서 탐색 횟수가 더욱 줄어들 것 같습니다.

기존 코드

for y in range(1, n-1):
        for x in range(1, n-1):
            if grid[y][x]: cores.append((y, x))
...
cy, cx = cores[cidx]

추가 로직

# 코어를 가장자리와 가까운 순으로 오름차순 정렬
cores.sort(key=lambda c: min(c[0], c[1], n - 1 - c[0], n - 1 - c[1]))

3. 최댓값 표기법

  • 초기 최댓값으로 int(1e10)을 사용하고 계시는데, 사실 일반적인 케이스에선 크게 문제가 되지 않지만, float('inf')가 좀 더 의미적으로 명확하게 전달할 수 있을 것 같습니다!

@clarityth
clarityth merged commit 239ebf7 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