solve: [W01] SWEA 1767 프로세서 연결하기 - #4
Conversation
📝 WalkthroughWalkthroughSWEA 1767의 DFS·백트래킹 풀이 문서를 추가했습니다. 코어별 연결 및 비연결 분기, 전선 경로 충돌 검사와 복구, 연결 코어 수 우선 및 전선 길이 차순 최적화 로직을 설명하고 파이썬 구현을 제공합니다. Changes프로세서 연결하기 풀이
Estimated code review effort: 1 (Trivial) | ~5 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (1)
studies/week-01/clarityth/1767-프로세서 연결하기.md
| **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억) |
There was a problem hiding this comment.
🚀 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 -nRepository: 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
| 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)) |
There was a problem hiding this comment.
📐 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.
| 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
left a comment
There was a problem hiding this comment.
코드도 무척 간결하고 주석이 친절하게 써있어서 모든 코드들이 어떤 역할을 하는지 쉽게 이해할 수 있었습니다. 저도 flag가 있는 코드를 작성했습니다. 있는편이 코드의 로직을 더 잘 이해할 수 있지 않나 생각합니다.
📌 이번 PR 내용
✅ 푼 문제 (SWEA)
🧾 5요소 체크리스트
각 풀이에 아래 5요소를 모두 작성했는지 확인합니다.
📋 규칙 체크
studies/week-XX/<깃허브ID>/<문제번호>-<문제이름>.md)💬 리뷰어에게
🧠 이번 주 회고 (한 줄)
스터디 화이팅!!
Summary by CodeRabbit