Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ bin/
*.in
*.out

# OS
.DS_Store
60 changes: 60 additions & 0 deletions notes/java/bfs-dfs/Program.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package practice.bfs;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;

public class Program {
public static void main(String[] args) {
/*
* (1)
* / | \
* (2) (3) (4)
* / \ / | \
* (5) (6)(7)(8)(9)
*/
final int[][] edges = { // 노드는 1번부터 시작
{1, 2}, {1, 3}, {1, 4},
{2, 5}, {2, 6},
{4, 7}, {4, 8}, {4, 9},
};
final int nodeCount = 9;

// 그래프를 자료형에 저장
List<List<Integer>> graph = new ArrayList<>();
for (int count = 0; count <= nodeCount; count++) graph.add(new ArrayList<>());
for (int[] edge : edges) graph.get(edge[0]).add(edge[1]);

// BFS
Queue<Integer> bfsQueue = new ArrayDeque<>();
bfsQueue.offer(1);

System.out.println("BFS");
while (!bfsQueue.isEmpty()) {
int nodeIndex = bfsQueue.poll();
System.out.println(nodeIndex);

for (int child : graph.get(nodeIndex)) {
bfsQueue.offer(child);
}
}
System.out.println();

// DFS
Stack<Integer> dfsStack = new Stack<>();
dfsStack.push(1);

System.out.println("DFS");
while (!dfsStack.isEmpty()) {
int nodeIndex = dfsStack.pop();
System.out.println(nodeIndex);

for (int child : graph.get(nodeIndex)) {
dfsStack.push(child);
}
}

}
}
102 changes: 102 additions & 0 deletions notes/java/heap-sort/Program.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package practice.heap;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Program {
private static class PriorityQueue<T extends Comparable<T>> {
private List<T> memory = new ArrayList<>();

public PriorityQueue() { memory.add(null); }

public void push(T item) {
memory.add(item);

int index = memory.size() - 1;
int parentIndex = index / 2;

while (parentIndex >= 1 && compareIndex(parentIndex, item)) {
Collections.swap(memory, parentIndex, index);

index = parentIndex;
parentIndex /= 2;
}
}

public T pop() {
final T item = memory.get(1);
int last = memory.size() - 1;

memory.set(1, memory.get(last));
memory.remove(last--);

int index = 1;
int childIndex = getChildIndex(index * 2);

while (childIndex <= last && compareIndex(index, childIndex)) {
Collections.swap(memory, index, childIndex);

index = childIndex;
childIndex = getChildIndex(index * 2);
}

return item;
}

private boolean compareIndex(int indexA, int indexB) {
return memory.get(indexA).compareTo(memory.get(indexB)) > 0;
}

private boolean compareIndex(int indexA, T value) {
return memory.get(indexA).compareTo(value) > 0;
}

private int getChildIndex(int index) {
final int size = memory.size();
if (index >= size) return size;
if (index == size - 1) return index;
if (compareIndex(index, index + 1)) index++;
return index;
}

public boolean isEmpty() { return memory.size() < 2; }
@Override public String toString() { return "PriorityQueue " + memory; }
}

private static <T extends Comparable<T>> Object[] heapSort(T[] arr) {
// 입력된 데이터를 모두 최소 힙에 입력한다
PriorityQueue<T> priorityQueue = new PriorityQueue<>();
for (T item : arr) priorityQueue.push(item);
System.out.println(priorityQueue);

// 최소 힙에 있는 데이터를 모두 pop 하여 정렬한다
List<T> result = new ArrayList<>();
while (!priorityQueue.isEmpty()) {
result.add(priorityQueue.pop());
System.out.println(priorityQueue);
}

// 결과 반환
return result.toArray();
}

public static void main(String[] args) {
// 정렬할 배열 준비
Integer[] arr = {4, 3, 5, 6, 3, 6, 899, 32, 54, 6, 7};

// 최소 힙 정렬
Object[] sortedArr = heapSort(arr);
System.out.println();

// 정렬 결과를 정수 배열로 변환하여 출력
Integer[] sortedIntArr = Arrays.copyOf(sortedArr, arr.length, Integer[].class);
System.out.println("heap sort: " + Arrays.toString(sortedIntArr));

// 결과 비교
Arrays.sort(arr);
System.out.println("sort : " + Arrays.toString(arr));
System.out.println("compare : " + Arrays.equals(arr, sortedIntArr));
}
}
132 changes: 132 additions & 0 deletions problems/SWEA/p1210/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/*
* (1210) [S/W 문제해결 기본] 2일차 - Ladder1
* https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV14ABYKADACFAYh&categoryId=AV14ABYKADACFAYh&categoryType=CODE&problemTitle=1210&orderBy=FIRST_REG_DATETIME&selectCodeLang=ALL&select-1=&pageSize=10&pageIndex=1
*/

package swea.p1210;

import java.io.*;
import java.util.*;

/**
* SW Expert Academy - 1210. [S/W 문제해결 기본] 2일차 - Ladder1
* @author YeJun, Jung
*
* @see #main(String[])
* 1. 입출력을 초기화한다.
* 2. 총 10개의 테스트 케이스를 반복 처리한다.
* 3. 각 테스트 케이스의 번호를 입력받고 솔루션 인스턴스를 생성하여 실행한다.
*
* @see #Solution(int)
* 4. 현재 테스트 케이스 번호를 멤버 변수에 저장한다.
*
* @see #run()
* 5. 입력(input), 해결(solve), 출력(print) 로직을 순차적으로 수행한다.
*
* @see #input()
* 6. 100x100 크기의 사다리 판(board) 정보를 입력받는다.
* 7. 입력 과정에서 값이 '2'인 도착 지점의 좌표(goalX, goalY)를 찾아 저장한다.
*
* @see #solve()
* 8. 도착점(goalX, goalY)에서 시작하여 위쪽 방향으로 역추적 시뮬레이션을 시작한다.
* 9. 현재 위치에서 좌/우에 가로축('1')이 있는지 확인한다.
* 9-1. 왼쪽(cx - 1)에 길이 있다면, 왼쪽 길이 끝날 때까지 $x$ 좌표를 감소시킨다.
* 9-2. 왼쪽에 길이 없고 오른쪽(cx + 1)에 길이 있다면, 오른쪽 길이 끝날 때까지 $x$ 좌표를 증가시킨다.
* 10. 좌우 이동이 끝났거나 없다면 위쪽(cy - 1)으로 한 칸 이동한다.
* 11. $y$ 좌표가 0에 도달했을 때의 $x$ 좌표가 시작점이므로 answer에 저장한다.
*
* @see #print()
* 12. 계산된 시작점의 $x$ 좌표를 형식에 맞춰 출력한다.
*/
public class Solution {
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
static StringTokenizer line;

public static void main(String[] args) throws IOException {
// 1. 입출력을 초기화한다.
final int testCount = 10;

// 2. 총 10개의 테스트 케이스를 반복 처리한다.
for (int testCase = 1; testCase <= testCount; testCase++) {
// 3. 테스트 케이스 번호 읽기 및 솔루션 실행
reader.readLine();
new Solution(testCase).run();
}
}

// ----------------------------------------------------------

private final int BOARD_SIZE = 100;

private int testCase;
private int answer;

private char[][] board;
private int goalX;
private int goalY;

public Solution(int testCase) {
// 4. 멤버 변수를 초기화한다.
this.testCase = testCase;
}

public void run() throws IOException {
// 5. 입력, 해결, 출력 순서로 실행한다.
input();
solve();
print();
}

private void input() throws IOException {
// 6. 사다리 판 정보를 저장할 배열 생성
board = new char[BOARD_SIZE][BOARD_SIZE];

for (int y = 0; y < BOARD_SIZE; y++) {
getLine();
for (int x = 0; x < BOARD_SIZE; x++) {
board[y][x] = line.nextToken().charAt(0);

// 7. 도착 지점('2')의 좌표를 저장한다.
if (board[y][x] == '2') {
goalX = x;
goalY = y;
}
}
}
}

private void solve() {
// 8. 도착점에서 역순으로 올라가기 위한 현재 좌표 설정
int cx = goalX, cy = goalY;

// 11. y가 0(최상단)에 도달할 때까지 반복
while (cy > 0) {
boolean check = true;

// 9-1. 왼쪽 방향으로 이동 가능한지 확인하고 끝까지 이동
for (; cx > 0 && board[cy][cx - 1] == '1'; cx--, check = false);

// 9-2. 왼쪽으로 이동하지 않았을 경우에만 오른쪽 방향 확인 및 이동
for (; check && cx < BOARD_SIZE - 1 && board[cy][cx + 1] == '1'; cx++);

// 10. 한 층 위로 이동
cy--;
}

// 최종 시작점 x 좌표 저장
answer = cx;
}

private void print() throws IOException {
// 12. 정답을 화면에 출력한다.
writer.write("#" + testCase + " " + answer + "\n");
writer.flush();
}

// ----------------------------------------------------------

private static void getLine() throws IOException {
line = new StringTokenizer(reader.readLine().trim());
}
}
Loading