Skip to content

[이준희-10주차 알고리즘 스터디] #13

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 16 commits into
base: junhee325/week10
Choose a base branch
from

Conversation

JHLEE325
Copy link
Contributor

@JHLEE325 JHLEE325 commented Mar 31, 2025

🚀 싸피 15반 알고리즘 스터디 10주차 [이준희]

📌 문제 풀이 개요

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

✅ 문제 해결 여부

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

💡 풀이 방법

문제 1: 최소 스패닝 트리

문제 난이도
골드 4

문제 유형
그래프

접근 방식 및 풀이
MST를 구하는 문제였습니다. 강의 시간에 배운 union, find 메소드를 이용하여 구현했습니다.

static int find(int a) {
		if (a == parents[a])
			return a;
		return parents[a] = find(parents[a]);
	}
	
	static boolean union(int a, int b) {
		int aRoot = find(a);
		int bRoot = find(b);

		if (aRoot == bRoot)
			return false;

		parents[bRoot] = aRoot;
		return true;
	}

무향 그래프였기 때문에 입력 받을 때 양방향으로 데이터를 저장했습니다.


문제 2: 파티

문제 난이도
골드 4

문제 유형
그래프

접근 방식 및 풀이
한 마을 까지 왕복 거리가 가장 먼 사람을 구하는 문제였습니다.
한 마을로 도착하는 다익스트라와, 그 마을에서 다시 돌아가는 다익스트라를 각각 1회씩 사용하여 최대값을 찾았습니다.

int[] dist = Dijkstra(x);
		int[] dist2 = Dijkstra2(x);
		int max = 0;
		for (int i = 1; i <= n; i++) {
			max = Math.max(max, dist[i] + dist2[i]);
		}
		System.out.println(max);```

문제 3: 쉬운 최단거리

문제 난이도
실버 1

문제 유형
그래프

접근 방식 및 풀이
각 지점에서 목표지점까지의 최소 거리를 파악하는 문제였습니다.
bfs를 사용하여 각 지점별 최소 거리를 파악하였습니다.

 public static void bfs(int startY, int startX) {
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{startY, startX});
        dist[startY][startX] = 0; // 목표 지점의 거리는 0

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

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

                if (dy >= 0 && dy < n && dx >= 0 && dx < m && map[dy][dx] == 1 && dist[dy][dx] == -1) {
                    dist[dy][dx] = dist[y][x] + 1;
                    queue.offer(new int[]{dy, dx});
                }
            }
        }
    }

문제 4: 경로찾기

문제 난이도
실버 1

문제 유형
그래프

접근 방식 및 풀이
인접행렬이 주어졌을 때 각 위치에서 다른 위치로의 이동이 가능한지를 파악하는 문제였습니다.
플로이드-워셜 알고리즘을 사용했습니다.

for (int k = 1; k <= n; k++) { // 플로이드-워셜 알고리즘으로 모든 점에서 다른 모든 점으로의 거리 계산
			for (int i = 1; i <= n; i++) {
				for (int j = 1; j <= n; j++) {
					arr[i][j] = Math.min(arr[i][j], arr[i][k] + arr[k][j]);
				}
			}
		}

문제 5 : 뱀과 사다리 게임

문제 난이도
골드 5

문제 유형
그래프

접근 방식 및 풀이
사다리, 뱀이 존재하는 판에서 주사위를 굴려 100번째 칸 까지 갈 수 있는 최소한의 횟수를 구하는 문제였습니다. 횟수별로 bfs 를 사용하여구현했습니다.

 static int bfs(int start) {
        Queue<Integer> queue = new ArrayDeque<>();
        queue.add(start);
        visited[start] = true; // 시작 위치 방문 처리
        int count = 0; // 이동 횟수 카운트

        while (!queue.isEmpty()) {
            int size = queue.size(); // 현재 레벨의 크기 (한 번의 주사위 던지기 결과)
            count++;

            // 현재 레벨에 있는 모든 노드 처리
            for (int i = 0; i < size; i++) {
                int current = queue.poll();

                // 주사위 던지기 결과 (1부터 6까지)
                for (int dice = 1; dice <= 6; dice++) {
                    int next = current + dice;

                    // 범위를 벗어난 경우는 무시
                    if (next > 100) continue;

                    // 사다리나 뱀에 의한 이동 처리
                    if (arr[next] != 0) {
                        next = arr[next];
                    }

                    // 목표 지점인 100에 도달하면 이동 횟수 리턴
                    if (next == 100) {
                        return count;
                    }

                    // 방문하지 않은 위치라면 큐에 추가
                    if (!visited[next]) {
                        visited[next] = true;
                        queue.add(next);
                    }
                }
            }
        }

        return -1; // 100에 도달할 수 없는 경우는 없으므로 사실상 이 부분은 필요 없음
    }

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