Skip to content

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

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

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

Conversation

@clarityth

@clarityth clarityth 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)
  • 금요일 마감 전 제출 (해당 주 일정 확인)

💬 리뷰어에게

  1. 시간 복잡도가 높은 로직이어서, 가지치기를 넣어야 할 것 같은데 최초 풀이시, 마땅한 방법이 생각이 나지 않았습니다.
  2. 현재 방식 외에 다른 풀이가 있는지도 궁금합니다.
  3. flag 변수를 두는 방식 외에 좀 더 pythonic한 풀이 방법이 존재하는지 궁금합니다.

🧠 이번 주 회고 (한 줄)

스터디 화이팅!!

Summary by CodeRabbit

  • Documentation
    • SWEA 1767 ‘프로세서 연결하기’ 문제 풀이 문서를 추가했습니다.
    • DFS와 백트래킹을 활용한 해결 전략, 경로 검증 및 상태 복구 과정을 설명합니다.
    • 파이썬 구현 코드와 시간·공간 복잡도, 최적해 갱신 기준을 포함했습니다.

@github-actions
github-actions Bot requested a review from min9u July 24, 2026 06:15
@coderabbitai

coderabbitai Bot commented Jul 24, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

SWEA 1767의 DFS·백트래킹 풀이 문서를 추가했습니다. 코어별 연결 및 비연결 분기, 전선 경로 충돌 검사와 복구, 연결 코어 수 우선 및 전선 길이 차순 최적화 로직을 설명하고 파이썬 구현을 제공합니다.

Changes

프로세서 연결하기 풀이

Layer / File(s) Summary
DFS 백트래킹 풀이와 정답 갱신
studies/week-01/clarityth/1767-프로세서 연결하기.md
코어를 순차적으로 선택하거나 건너뛰며 네 방향의 직선 전선을 탐색합니다. visited로 경로 충돌을 검사하고, 탐색 후 경로를 복구하며 연결 코어 수를 우선하고 전선 길이를 차선으로 최적해를 갱신합니다.

Estimated code review effort: 1 (Trivial) | ~5 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed SWEA 1767 ‘프로세서 연결하기’ 풀이 문서 추가라는 변경 내용과 제목이 정확히 일치합니다.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch week01/clarityth

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/clarityth/1767-프로세서` 연결하기.md:
- Around line 38-46: DFS에 남은 코어 수를 활용한 상한 가지치기를 추가해, 현재 연결 코어 수와 남은 코어를 모두 사용해도
max_cores를 넘을 수 없는 상태는 즉시 반환하세요. 탐색 순서는 각 코어에서 연결 가능성이 높은 방향을 먼저 시도하도록 정렬해 유망한
분기를 우선 처리하고, 전체 복잡도 설명은 테스트케이스 수를 반영한 O(T·N·5^C)로 수정하세요.
- Around line 116-151: Refactor the connection-checking loop to use a helper
that returns the traversed path when the wire reaches outside the grid and
returns None when blocked by a core or visited cell. In the surrounding
backtracking logic, replace can_pass, cur_path, and wire state handling with the
helper result, using the returned path length for the wire length while
preserving visited marking, DFS recursion, and rollback.
🪄 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: a34c2a56-4d32-439a-80d9-6fc529a53514

📥 Commits

Reviewing files that changed from the base of the PR and between 5b5591a and 2fbdf62.

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

Comment on lines +38 to +46
**O(N * 5^C)** — (단, C는 가장자리를 제외한 코어의 개수)

각 코어마다 4가지 방향으로 전선을 연결하는 경우와 연결을 포기하는 경우를 합쳐 총 5가지의 선택지가 존재

모든 코어에 대해 재귀 탐색을 진행하므로 상태 공간 트리의 최대 크기는 5^C

각 방향 탐색 시 전선의 배치 가능 여부를 확인하고 경로를 기록하는 내부 while 루프에서 최대 N번의 연산이 수행되므로 전체 시간 복잡도는 O(N * 5^C)

문제의 조건이 7 <= N <= 12, 1 <= C <= 12이므로, 최악의 경우 연산 횟수는 12 * 5^12에 비례(약 29억)

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

file='studies/week-01/clarityth/1767-프로세서 연결하기.md'

printf 'FILE: %s\n' "$file"
wc -l "$file"
printf '\n--- outline / nearby structure ---\n'
sed -n '1,220p' "$file" | cat -n

Repository: DevJunz/coding-test-study-template

Length of output: 6058


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file='studies/week-01/clarityth/1767-프로세서 연결하기.md'

echo '--- relevant slices ---'
sed -n '1,180p' "$file" | nl -ba | sed -n '1,180p'

Repository: DevJunz/coding-test-study-template

Length of output: 236


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file='studies/week-01/clarityth/1767-프로세서 연결하기.md'

rg -n "시간 복잡도|공간 복잡도|핵심 풀이|실제 코드|def |class |return|while|dfs|backtrack|visited|can_pass|cur_path|wire" "$file"

Repository: DevJunz/coding-test-study-template

Length of output: 1867


상한 가지치기를 넣으세요.
복잡도 계산 자체는 테스트케이스당 O(N·5^C)로 맞지만, 전체는 O(T·N·5^C)입니다. 현재 DFS는 남은 코어로도 max_cores를 넘지 못하는 상태를 자르지 않아, N=12, C=12에서는 Python에서 TLE 위험이 큽니다. 이 pruning을 추가하고, 유망한 방향부터 먼저 탐색하세요.

🤖 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/clarityth/1767-프로세서` 연결하기.md around lines 38 - 46, DFS에 남은 코어
수를 활용한 상한 가지치기를 추가해, 현재 연결 코어 수와 남은 코어를 모두 사용해도 max_cores를 넘을 수 없는 상태는 즉시 반환하세요.
탐색 순서는 각 코어에서 연결 가능성이 높은 방향을 먼저 시도하도록 정렬해 유망한 분기를 우선 처리하고, 전체 복잡도 설명은 테스트케이스 수를
반영한 O(T·N·5^C)로 수정하세요.

Source: Path instructions

Comment on lines +116 to +151
can_pass = False # 이동 가능 여부 저장
cur_path = [] # 이동 경로를 저장
wire = 0 # 전선 길이 저장

while True:
# 다음 위치 이동
ny += dy[i]
nx += dx[i]

if 0 <= ny < N and 0 <= nx < N:
# 다른 코어가 위치하고 있거나, 이전에 방문했다면(교차) 진행 불가
if grid[ny][nx] == 1 or (ny, nx) in visited:
break

# 이동 경로에 기록
cur_path.append((ny, nx))

# 범위 밖까지 도달했다면 도달 가능 변수 업데이트
else:
can_pass = True
break

wire += 1 # 전선 길이 증가

# 백트래킹
if can_pass:
# 이동 경로를 visited에 기록
for path_y, path_x in cur_path:
visited.add((path_y, path_x))

# 해당 경로를 선택한 채, 다음 dfs 진행
dfs(idx+1, visited, tot_cores+1, tot_wire_len+wire)

# 원상 복구
for path_y, path_x in cur_path:
visited.remove((path_y, path_x))

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 | 🔵 Trivial | ⚡ Quick win

can_pass 플래그를 반환값 기반 연결 검사로 단순화할 수 있습니다.

현재 로직은 can_pass, cur_path, wire를 별도로 관리해 상태 흐름이 길어집니다. 연결 가능한 경로를 반환하고, 실패 시 None을 반환하는 helper로 분리하면 wire == len(path)도 자연스럽게 보장됩니다.

개선 예시
+    def find_path(y, x, direction, visited):
+        path = []
+        while True:
+            y += dy[direction]
+            x += dx[direction]
+
+            if not (0 <= y < N and 0 <= x < N):
+                return path
+            if grid[y][x] == 1 or (y, x) in visited:
+                return None
+
+            path.append((y, x))
+
     def dfs(idx, visited, tot_cores, tot_wire_len):
         ...
         for i in range(4):
-            ny, nx = core_pos[idx][0], core_pos[idx][1]
-            can_pass = False
-            cur_path = []
-            wire = 0
-
-            while True:
-                ...
+            cur_path = find_path(*core_pos[idx], i, visited)
+            if cur_path is None:
+                continue
 
-            if can_pass:
-                ...
-                dfs(idx+1, visited, tot_cores+1, tot_wire_len+wire)
-                ...
+            for path_y, path_x in cur_path:
+                visited.add((path_y, path_x))
+            dfs(idx + 1, visited, tot_cores + 1,
+                tot_wire_len + len(cur_path))
+            for path_y, path_x in cur_path:
+                visited.remove((path_y, path_x))
📝 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
can_pass = False # 이동 가능 여부 저장
cur_path = [] # 이동 경로를 저장
wire = 0 # 전선 길이 저장
while True:
# 다음 위치 이동
ny += dy[i]
nx += dx[i]
if 0 <= ny < N and 0 <= nx < N:
# 다른 코어가 위치하고 있거나, 이전에 방문했다면(교차) 진행 불가
if grid[ny][nx] == 1 or (ny, nx) in visited:
break
# 이동 경로에 기록
cur_path.append((ny, nx))
# 범위 밖까지 도달했다면 도달 가능 변수 업데이트
else:
can_pass = True
break
wire += 1 # 전선 길이 증가
# 백트래킹
if can_pass:
# 이동 경로를 visited에 기록
for path_y, path_x in cur_path:
visited.add((path_y, path_x))
# 해당 경로를 선택한 채, 다음 dfs 진행
dfs(idx+1, visited, tot_cores+1, tot_wire_len+wire)
# 원상 복구
for path_y, path_x in cur_path:
visited.remove((path_y, path_x))
def find_path(y, x, direction, visited):
path = []
while True:
y += dy[direction]
x += dx[direction]
if not (0 <= y < N and 0 <= x < N):
return path
if grid[y][x] == 1 or (y, x) in visited:
return None
path.append((y, x))
cur_path = find_path(*core_pos[idx], i, visited)
if cur_path is None:
continue
# 이동 경로를 visited에 기록
for path_y, path_x in cur_path:
visited.add((path_y, path_x))
# 해당 경로를 선택한 채, 다음 dfs 진행
dfs(idx + 1, visited, tot_cores + 1, tot_wire_len + len(cur_path))
# 원상 복구
for path_y, path_x in cur_path:
visited.remove((path_y, path_x))
🤖 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/clarityth/1767-프로세서` 연결하기.md around lines 116 - 151, Refactor
the connection-checking loop to use a helper that returns the traversed path
when the wire reaches outside the grid and returns None when blocked by a core
or visited cell. In the surrounding backtracking logic, replace can_pass,
cur_path, and wire state handling with the helper result, using the returned
path length for the wire length while preserving visited marking, DFS recursion,
and rollback.

Source: Path instructions

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

코드도 무척 간결하고 주석이 친절하게 써있어서 모든 코드들이 어떤 역할을 하는지 쉽게 이해할 수 있었습니다. 저도 flag가 있는 코드를 작성했습니다. 있는편이 코드의 로직을 더 잘 이해할 수 있지 않나 생각합니다.

@min9u
min9u merged commit 6002de2 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