Skip to content

[강신지-11주차 알고리즘 스터디] #16

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 15 commits into
base: akstp1717/week11
Choose a base branch
from

Conversation

ksinji
Copy link
Contributor

@ksinji ksinji commented Apr 6, 2025

🚀 싸피 15반 알고리즘 스터디 11주차 [강신지]

📌 문제 풀이 개요

  • 이번 PR에서는 다음 5문제의 풀이를 포함합니다.
  • 각 문제에 대한 풀이 과정과 접근 방식을 설명합니다.

✅ 문제 해결 여부

  • 문제 1
  • 문제 2
  • 문제 3
  • 문제 4
  • 문제 5

💡 풀이 방법

문제 1: 알고스팟

문제 난이도
골드 4

문제 유형
그래프

접근 방식 및 풀이
시작점에서 도착점까지 도달하는 데 필요한 최소 벽 부수기 횟수를 구하는 문제입니다.
0-1 BFS를 사용하여 각 칸까지의 최소 벽 부수기 횟수를 갱신하는 방식으로 해결했습니다.

static void bfs(){
    Deque<int[]> d = new LinkedList<>();
    d.add(new int[]{0, 0});
    wallCnt[0][0] = 0;

    while (!d.isEmpty()){
        int[] current = d.poll();
        int x = current[0];
        int y = current[1];

        for (int i=0; i<4; i++){
            int nx = x + dx[i];
            int ny = y + dy[i];

            if (!isOK(nx, ny)) continue;

            int wall = wallCnt[x][y] + map[nx][ny];

            if (wall < wallCnt[nx][ny]){
                wallCnt[nx][ny] = wall;
                if (map[nx][ny] == 0){
                    d.addFirst(new int[]{nx, ny});
                } else {
                    d.addLast(new int[]{nx, ny});
                }
            }
        }
    }
}

문제 2: 거울설치

문제 난이도
골드 3

문제 유형
그래프

접근 방식 및 풀이
한쪽 문에서 다른쪽 문을 보기 위해 필요한 최소 거울 설치 횟수를 구하는 문제입니다.
각 위치와 방향별로 상태를 관리하면서 우선순위 큐를 통해 최소 거울 설치 횟수를 구했습니다.

while (!pq.isEmpty()){
    // State -- 현재 위치와 진행 방향, 거울 설치 횟수
    State cur = pq.poll();
    int x = cur.x, y = cur.y, d = cur.d, cnt = cur.cnt;
    
    // 이미 더 적은 거울 설치 횟수로 도달한 위치라면 continue
    if (cnt > dist[x][y][d]) continue;

    // 도착 문에 도달
    if (x == endX && y == endY) {
        System.out.println(cnt);
        return;
    }

    // d 방향으로 전진
    int nx = x + dx[d];
    int ny = y + dy[d];

    // 유효한 좌표이며 벽이 아니라면
    if (isOK(nx, ny) && grid[nx][ny] != '*') {
        // 기존 비용과 전진 후의 비용 비교 
        if (cnt < dist[nx][ny][d]){
            dist[nx][ny][d] = cnt;
            pq.offer(new State(nx, ny, d, cnt));
        }
    }

    // 현재 거울 설치 가능 위치인 경우
    if (grid[x][y] == '!') {
        // 방향 전환
        int left = (d + 3) % 4;
        int right = (d + 1) % 4;
        
        // 왼쪽 회전
        if (isOK(x + dx[left], y + dy[left]) && grid[x + dx[left]][y + dy[left]] != '*') {
            if (cnt + 1 < dist[x][y][left]) {
                dist[x][y][left] = cnt + 1;
                pq.offer(new State(x, y, left, cnt + 1));
            }
        }
        
        // 오른쪽 회전
        if (isOK(x + dx[right], y + dy[right]) && grid[x + dx[right]][y + dy[right]] != '*') {
            if (cnt + 1 < dist[x][y][right]) {
                dist[x][y][right] = cnt + 1;
                pq.offer(new State(x, y, right, cnt + 1));
            }
        }
    }
}

회전 연산을 쉽게 하기 위해, 주로 사용하던 '상하좌우' 순서가 아닌 '상우좌하' 순서로 하였습니다.


문제 3: 2×n 타일링 2

문제 난이도
실버 3

문제 유형
DP

접근 방식 및 풀이
2×n 크기의 타일을 채우는 경우의 수를 구하는 문제로, 점화식을 세워 DP로 풀었습니다.

dp[1] = 1;
dp[2] = 3;
for (int i = 3; i <= N; i++) {
    dp[i] = (dp[i-2]*2 + dp[i-1]) % 10007;
}

문제 4: LCS

문제 난이도
골드 5

문제 유형
DP

접근 방식 및 풀이
최장 공통 부분 수열의 길이를 구하는 문제입니다.
2차원 DP 배열을 이용해 문자가 일치하면 대각선 값, 불일치할 경우 좌/상 중 최댓값을 선택하는 방식으로 해결했습니다.

for (int i = 1; i <= a.length(); i++) {
    for (int j = 1; j <= b.length(); j++) {
        if (A[i] == B[j]) dp[i][j] = dp[i-1][j-1] + 1;
        else dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]);
    }
}

문제 5 : 평범한 배낭

문제 난이도
골드 5

문제 유형
DP

접근 방식 및 풀이
주어진 무게 제한 내에서 최대 가치를 구하는 문제입니다.
각 물건을 포함하거나 제외하는 경우를 2차원 DP 배열을 통해 비교하며 최적의 가치를 구하는 방식으로 해결했습니다.

for (int i = 1; i <= N; i++) {
    for (int j = 1; j <= K; j++) {
        dp[i][j] = dp[i-1][j];
        if (j - weight[i] >= 0) {
            dp[i][j] = Math.max(dp[i-1][j], dp[i-1][j - weight[i]] + value[i]);
        }
    }
}

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.

1 participant