Skip to content

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

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/week13
Choose a base branch
from

Conversation

JHLEE325
Copy link
Contributor

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

📌 문제 풀이 개요

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

✅ 문제 해결 여부

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

💡 풀이 방법

문제 1: 스티커

문제 난이도
실버 1

문제 유형
DP

접근 방식 및 풀이
n번째 칸의 스티커를 선택할 때 n-2번째와 n-1번째칸을 고려하여 dp 계산하였습니다.

if (n == 1) { // 1칸짜리 일 경우
				sb.append(Math.max(sticker[0][0], sticker[1][0]) + "\n");
				continue;
			}

			else { // 2칸 이상인 경우
				dp[0][0] = sticker[0][0];
				dp[1][0] = sticker[1][0];

				dp[0][1] = dp[1][0] + sticker[0][1];
				dp[1][1] = dp[0][0] + sticker[1][1];

				for (int i = 2; i < n; i++) { // dp 계산
					for (int j = 0; j < 2; j++) {
						dp[j][i] += Math.max(dp[(j * -1) + 1][i - 1], dp[(j * -1) + 1][i - 2]);
						dp[j][i] += sticker[j][i];
					}
				}

				sb.append(Math.max(dp[0][n - 1], dp[1][n - 1]) + "\n");
			}

문제 2: 곱셈

문제 난이도
실버 1

문제 유형
수학

접근 방식 및 풀이
제곱을 분할하고 나머지 공식을 활용하는 문제였습니다. 컴퓨팅사고력 시간에 배운 내용을 활용하였습니다.

static long pow(long a, int b) { // 큰 수 제곱 방식 활용
		if (b == 0)
			return 1;
		long half = pow(a, b / 2);
		long result = (half * half) % MOD;
		if (b % 2 == 1)
			result = (result * a) % MOD;
		return result;
	}

문제 3: 후위 표기식

문제 난이도
골드 2

문제 유형
자료구조

접근 방식 및 풀이
숫자 숫자 연산자 로 나와야 되는 후위 표기법과 사칙연산 순서에 따라 구현했습니다.

static String topostfix(String str) {
		StringBuilder sb = new StringBuilder();
		Stack<Character> stack = new Stack<>();

		for (char c : str.toCharArray()) {
			if (isAlphabet(c)) { // 알파벳이면 바로 입력
				sb.append(c);
			} else if (c == '(') { // 여는 괄호 나오면 스택에 저장
				stack.push(c);
			} else if (c == ')') { // 닫는 괄호 나오면
				while (!stack.isEmpty() && stack.peek() != '(') { // 여는 괄호 전까지
					sb.append(stack.pop()); // 스택에서 빼서 입력
				}
				stack.pop();
			} else if (isOperater(c)) { // 연산자인 경우
				while (!stack.isEmpty() && priority(stack.peek()) >= priority(c)) {
					sb.append(stack.pop()); // 스택에 들어있는 연산자가 현재 연산자보다 우선순위가 높으면 스택에서 꺼내서 입력
				}
				stack.push(c); // 연산자를 스택에 저장
			}
		}

		while (!stack.isEmpty()) {
			sb.append(stack.pop()); // 나머지 연산자 후위표기로 입력
		}

		return sb.toString();
	}

	static boolean isAlphabet(char c) { // 알파벳 대문자가 숫자 대용이므로 판단
		return c - 'A' >= 0 && c - 'A' <= 26;
	}

	static boolean isOperater(char c) { // 연산자인지 판단
		return c == '*' || c == '/' || c == '+' || c == '-';
	}

	static int priority(char c) { // 연산자 우선순위 판단
		if (c == '+' || c == '-')
			return 1;
		if (c == '/' || c == '*')
			return 2;
		return 0;
	}

문제 4: 벽 부수고 이동하기

문제 난이도
골드 3

문제 유형
그래프

접근 방식 및 풀이
벽을 부수는 경우와 부수지 않는 경우를 고려하여 3차원 visited 배열을 사용하여 풀었습니다.

static void bfs() {
		Queue<Cell> list = new ArrayDeque<>();
		list.add(new Cell(0, 0, 0));
		visited[0][0][0] = true;
		int step = 1;

		while (!list.isEmpty()) {
			int size = list.size();
			for (int s = 0; s < size; s++) {
				Cell cur = list.poll();
				if (cur.y == n - 1 && cur.x == m - 1) {
					System.out.println(step);
					return;
				}
				for (int d = 0; d < 4; d++) {
					int dy = cur.y + dir[d][0];
					int dx = cur.x + dir[d][1];
					if (dy >= 0 && dy < n && dx >= 0 && dx < m) {
						if (map[dy][dx] == 1 && cur.wall == 0 && !visited[dy][dx][1]) {
							visited[dy][dx][1] = true;
							list.add(new Cell(dy, dx, 1));
						} else if (map[dy][dx] == 0 && !visited[dy][dx][cur.wall]) {
							visited[dy][dx][cur.wall] = true;
							list.add(new Cell(dy, dx, cur.wall));
						}
					}
				}
			}
			step++;
		}
		System.out.println("-1");
	}

문제 5 : 숨바꼭질 3

문제 난이도
골드 5

문제 유형
그래프

접근 방식 및 풀이
bfs와 같은 방식을 풀되 가중치를 0과 1로 한 0-1 bfs를 활용했습니다

static void bfs() { // bfs처럼 탐색하면서 찾기
		while (!list.isEmpty()) {
			Node cur = list.poll();
			if (visited[cur.x])
				continue;
			visited[cur.x] = true;

			if (cur.x == k) {
				System.out.println(cur.time);
				return;
			}
			int dx = cur.x * 2;
			if (dx <= 100000 && !visited[dx]) {
				list.add(new Node(dx, cur.time));
			}
			dx = cur.x - 1;
			if (dx >= 0 && !visited[dx]) {
				list.add(new Node(dx, cur.time + 1));
			}
			dx = cur.x + 1;
			if (dx <= 100000 && !visited[dx]) {
				list.add(new Node(dx, cur.time + 1));
			}
		}
	}

문제 6 : 웜홀

문제 난이도
골드 3

문제 유형
그래프

접근 방식 및 풀이
벨만-포드 알고리즘에 대해 학습 후 풀이하겠습니다

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