diff --git a/.gitignore b/.gitignore index 86689ad..c9aac5b 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,12 @@ /coding_test_study.iml /out/ /coding_test_study/.idea/workspace.xml +/build.gradle +/gradlew +/gradlew.bat +/settings.gradle +/src/main/java/week01/ +/src/main/java/week02/ +/src/main/java/week03/ +/src/main/java/week04/ +/src/main/java/week05/ diff --git a/src/main/java/week11/gahyun/p1/Solution.java b/src/main/java/week11/gahyun/p1/Solution.java new file mode 100644 index 0000000..f448458 --- /dev/null +++ b/src/main/java/week11/gahyun/p1/Solution.java @@ -0,0 +1,88 @@ +package week11.gahyun.p1; + +/** + * 2x2이므로 dfs아닌 완전 탐색 + * 헷갈린점: + * (1) 블록 내리기 + * - block[r] 아래부터 위로 탐색 + * - writeRow는 어디까지 썼는지 나타내는 포인터 (r과 동일하게 아래부터) + * - if) block[r] 빈칸 아니면 + * - block[writeRow] = block[r] + * - writeRow--; + * - writeRow ~ 0까지 빈칸으로 채우기 + * (2) mark 배열 둬야 함 하나의 배열로 처리 불가 + */ + +class Solution { + static char[][] block; + static boolean[][] marked; + public int solution(int m, int n, String[] board) { + int totalRemoveCnt = 0; + block = new char[m][n]; + marked = new boolean[m][n]; + + initBlock(board,m,n); //board-> block + + while (true){ + //1) 2x2 체크 + mark(m,n); + + //2) 체크된 곳 빈칸 처리 + int removeCnt = erase(m,n); + if (removeCnt==0) break; + totalRemoveCnt+=removeCnt; + + //3) 지워진 곳 채우기 + fall(m,n); + } + + return totalRemoveCnt; + } + + private static void fall(int m, int n) { + for (int c = 0; c < n; c++) { + int writeRow = m-1; + for (int r=m-1;r>=0;r--){ + if (block[r][c]!=' '){ + block[writeRow][c] = block[r][c]; + writeRow--; + } + } + for (int r = writeRow;r>=0;r--){ + block[r][c] = ' '; + } + } + } + + private static int erase(int m, int n){ + int removeCnt =0; + for (int r=0;r bridge = new LinkedList<>(); + for (int i=0;i0){ + time++; + load_w-=bridge.poll(); // 트럭 건넘 -> 무게 차감 + + if (ind 무게 증가 + } + else bridge.offer(0); //현재 트럭 건널 수 없음 + } + + return time; + } +} + diff --git a/src/main/java/week11/gahyun/p3/Solution.java b/src/main/java/week11/gahyun/p3/Solution.java new file mode 100644 index 0000000..00edbff --- /dev/null +++ b/src/main/java/week11/gahyun/p3/Solution.java @@ -0,0 +1,32 @@ +package week11.gahyun.p3; + +import java.util.*; + +/** + * 접근 방식 + * - 처음에는 Queue로 풀었는데 split하는게 더 효율적 + * - 0+는 0이 한개 이상인 것 + * - n을 k진수로 변환: Intereger.toString(n,k) + */ +class Solution { + public int solution(int n, int k) { + int cnt = 0; + + String numK = Integer.toString(n,k); + String[] subset = numK.split("0+"); + for (String num : subset){ + if (num.equals("")) continue; + if (isPrime(Long.parseLong(num))) cnt++; + } + + return cnt; + } + + private static boolean isPrime(long num){ //소수여부 판별 + if (num<2) return false; + for (long i=2;i*i<=num;i++){ + if (num%i==0) return false; + } + return true; + } +} diff --git a/src/main/java/week11/gahyun/p4/Solution.java b/src/main/java/week11/gahyun/p4/Solution.java new file mode 100644 index 0000000..c4b7bc3 --- /dev/null +++ b/src/main/java/week11/gahyun/p4/Solution.java @@ -0,0 +1,34 @@ +package week11.gahyun.p4; + +import java.util.Stack; + +class Solution { + public int solution(int[] order) { + //박스 초기화 + int[] boxes = new int[order.length]; + Stack stk = new Stack<>(); + int boxInd = 0,cnt = 0; + + for (int i=0;i TreeMap + */ +class Solution { + public int[] solution(int[] fees, String[] records) { + + Map map = new TreeMap<>(); //차번호, 차 + for (String record: records){ + String[] data = record.split(" "); + + String[] time = data[0].split(":"); + int hour = Integer.valueOf(time[0]); + int min = Integer.valueOf(time[1]); + + String carNum = data[1]; + String cmd = data[2]; + if (!map.containsKey(carNum)){ + map.put(carNum,new Car()); + } + + Car car = map.get(carNum); + if (cmd.equals("IN")){ + car.entry(hour,min); + } + else { + car.out(hour,min); + } + + } + + int[] answer = new int[map.size()]; + int idx = 0; + for (Car car:map.values()){ + answer[idx++] = calculateFee(fees, car); + } + + return answer; + } + + private int calculateFee(int[] fees, Car car){ + int defaultMin = fees[0]; + int defaultFee = fees[1]; + int overMin = fees[2]; + int overFee = fees[3]; + + int totalTime = car.getTotalTime(); + + if (totalTime<=defaultMin) return defaultFee; + else + return defaultFee+(int)Math.ceil((totalTime-defaultMin)*1.0/overMin)*overFee; + } +} + +class Car { + boolean isEntry; //입차 여부 + int entryHour; //입차 시간 + int entryMin; //입차 분 + int totalTime = 0; + + public void entry(int entryHour, int entryMin){//입차 + this.entryHour = entryHour; + this.entryMin = entryMin; + isEntry = true; + } + + public void out(int outHour, int outMin){ //출차 + totalTime+= (outHour-entryHour)*60+(outMin-entryMin); //주차 시간 누적 + isEntry = false; + } + + public int getTotalTime(){ //누적시간 반환 + if (isEntry){//아직 출차 안함 + totalTime+= (23-entryHour)*60+(59-entryMin); + } + return totalTime; + } +} diff --git a/src/main/java/week11/gahyun/p6/Solution.java b/src/main/java/week11/gahyun/p6/Solution.java new file mode 100644 index 0000000..0fb5255 --- /dev/null +++ b/src/main/java/week11/gahyun/p6/Solution.java @@ -0,0 +1,49 @@ +package week11.gahyun.p6; + +import java.util.*; + +/**문제 요약 + * - 알파벳으로 단어 초기화 + * - 단어 일정 부분 자르기 + * - 해당 단어 있으면 한 글자 더해서 새로운 단어 만듦 + * - 기존 단어의 사전 번호 출력 + * - 새로운 단어 사전에 저장 + * 헷갈린 점 + * - w+=c를 하는 게 아니라 nextIdx계속 더해서 substring하기 + */ +class Solution { + public int[] solution(String msg) { + Map dict = new HashMap<>(); + List output = new ArrayList<>(); + initDict(dict); + int curIdx = 0, dictIdx=27; + + while (curIdx dict){ + int dictIdx = 1; + for (char c = 'A';c<='Z';c++){ + dict.put(c+"",dictIdx++); + } + } +} diff --git a/src/main/java/week11/gahyun/p7/Solution.java b/src/main/java/week11/gahyun/p7/Solution.java new file mode 100644 index 0000000..98fdb0c --- /dev/null +++ b/src/main/java/week11/gahyun/p7/Solution.java @@ -0,0 +1,38 @@ +package week11.gahyun.p7; + +import java.util.*; + +/** + * 접근 방법: 각 분을 인덱스화하여 카운트 + */ +class Solution { + static int maxCnt = 0; + public int solution(String[][] book_time) { + int limit = 23*60+59; + int[] cnt = new int[limit+1]; //00:00~23:59 점유 객실 수 + + for (int i=0;ilimit) endIdx = limit; + occupy(startIdx, endIdx,cnt); + } + + return maxCnt; + } + + private static void occupy(int startIdx, int endIdx, int[] cnt){ + for (int i=startIdx;i<=endIdx;i++){ + cnt[i]++; + maxCnt = Math.max(cnt[i],maxCnt); + } + } +} diff --git a/src/week01/gahyun/p1/Main.java b/src/week01/gahyun/p1/Main.java deleted file mode 100644 index a640b4a..0000000 --- a/src/week01/gahyun/p1/Main.java +++ /dev/null @@ -1,78 +0,0 @@ -package week01.gahyun.p1; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.LinkedList; -import java.util.Queue; -import java.util.StringTokenizer; - -/* - - 문제 링크: https://www.acmicpc.net/problem/2178 - - 메모리: 14988KB - - 시간: 112ms - */ -/* - - BFS 탐색 - - x,y 좌표 가지는 Pos - - 큐에서 현재 노드의 좌표 추출 - - 현재 노드로부터 유효한 상하좌우 노드 거리 계산(현 노드 거리 + 1) 및 큐에 저장 - */ -public class Main { - static int[][] graph, dis; - static int n, m; - // 상하좌우 - static int[] dx = {0, 0, -1, 1}; - static int[] dy = {1, -1, 0, 0}; - - public static void BFS() { - Queue queue = new LinkedList<>(); - //시작 노드 방문 - queue.offer(new Pos(0, 0)); - dis[0][0] = 1; - graph[0][0] = 0; - - while (!queue.isEmpty()) { - Pos cp = queue.poll(); //현재위치 - for (int i = 0; i < 4; i++) { //상하좌우 - int nx = cp.x + dx[i]; - int ny = cp.y + dy[i]; - if (nx >= 0 && nx <= n - 1 && ny >= 0 && ny <= m - 1 && graph[nx][ny] == 1) { - graph[nx][ny] = 0; //방문 - dis[nx][ny] = dis[cp.x][cp.y] + 1; //이전거리+1 - queue.offer(new Pos(nx, ny)); - } - } - } - } - - public static void main(String[] args) throws IOException { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - StringTokenizer st = new StringTokenizer(br.readLine()); - n = Integer.parseInt(st.nextToken()); - m = Integer.parseInt(st.nextToken()); - - graph = new int[n][m]; //이동가능여부 - dis = new int[n][m]; //거리 - - for (int i = 0; i < n; i++) { - String s = br.readLine(); - for (int j = 0; j < m; j++) { - graph[i][j] = s.charAt(j) - '0'; - } - } - - BFS(); - System.out.println(dis[n - 1][m - 1]); - } -} - -//x,y 좌표 -class Pos { - int x, y; - - public Pos(int x, int y) { - this.x = x; - this.y = y; - } -} diff --git a/src/week01/gahyun/p2/Main.java b/src/week01/gahyun/p2/Main.java deleted file mode 100644 index bbe0186..0000000 --- a/src/week01/gahyun/p2/Main.java +++ /dev/null @@ -1,74 +0,0 @@ -package week01.gahyun.p2; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.StringTokenizer; - -/* - - 문제 링크: https://www.acmicpc.net/problem/1303 - - 메모리: 16144KB - - 시간: 124ms - */ -/* - - 색깔 그래프 순회 - - DFS 탐색으로 연속된 영역 개수 세기 - - 매 호출마다 cnt++ - - 연속된 부분 있는지 탐색 - - 탐색 완료 후 cnt^2 더하기 - */ -public class Main { - static char[][] graph; - static boolean[][] visited; - static int cnt = 0, totalW = 0, totalB = 0; - static int n, m; - static int[] dx = {0, 0, -1, 1}; - static int[] dy = {1, -1, 0, 0}; - - public static void DFS(int x, int y, char t) { - visited[x][y] = true; // 현재 위치 방문 - cnt++; - for (int i = 0; i < 4; i++) { - int nx = x + dx[i]; - int ny = y + dy[i]; - if (nx >= 0 && nx < m && ny >= 0 && ny < n && graph[nx][ny] == t && !visited[nx][ny]) { - DFS(nx, ny, t); // 연속된 영역 탐색 - } - } - } - - public static void main(String[] args) throws IOException { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - - StringTokenizer st = new StringTokenizer(br.readLine()); - n = Integer.parseInt(st.nextToken()); //열 - m = Integer.parseInt(st.nextToken()); //행 - graph = new char[m][n]; - visited = new boolean[m][n]; - - for (int i = 0; i < m; i++) { - String s = br.readLine(); - for (int j = 0; j < n; j++) { - graph[i][j] = s.charAt(j); - } - } - - for (int i = 0; i < m; i++) { - for (int j = 0; j < n; j++) { - if (!visited[i][j]) { - if (graph[i][j] == 'W') { - cnt = 0; // 개수 초기화 - DFS(i, j, 'W'); - totalW += cnt * cnt; //연속된 영역 개수^2 - } else { //'B' - cnt = 0; - DFS(i, j, 'B'); - totalB += cnt * cnt; - } - } - } - } - - System.out.println(totalW + " " + totalB); - } -} diff --git a/src/week01/gahyun/p3/Main.java b/src/week01/gahyun/p3/Main.java deleted file mode 100644 index be24321..0000000 --- a/src/week01/gahyun/p3/Main.java +++ /dev/null @@ -1,98 +0,0 @@ -package week01.gahyun.p3; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.LinkedList; -import java.util.Queue; -import java.util.StringTokenizer; - -/* - - 문제 링크: https://www.acmicpc.net/problem/7569 - - 메모리: 125604KB - - 시간: 592ms - */ -/* - - BFS 탐색 로직은 1번과 동일, 차원만 증가 - - BFS 호출 전 : graph 순회하며 1인 지점 -> queue 삽입 - - BFS 호출 중 : 상하좌우 이동하며 0인 지점 1로 바꾸고 queue 삽입 - - BFS 호출 후 : graph 하나라도 0이면 사과 안 익음 -> -1 출력 - 모두 익음 -> 최대 거리(=일수) 출력 - */ -public class Main { - static int[][][] graph, dis; - static Queue queue = new LinkedList<>(); //main에서도 쓰임 - // 이동 가능한 좌표 - static int[] dx = {0, 0, -1, 1, 0, 0}; - static int[] dy = {-1, 1, 0, 0, 0, 0}; - static int[] dz = {0, 0, 0, 0, 1, -1}; - - static int h, n, m, remain; - - static void BFS() { - while (!queue.isEmpty()) { - Pos cp = queue.poll(); - for (int i = 0; i < 6; i++) { - int nx = cp.x + dx[i]; - int ny = cp.y + dy[i]; - int nz = cp.z + dz[i]; - if (nx >= 0 && nx < n && ny >= 0 && ny < m && nz >= 0 && nz < h && graph[nz][nx][ny] == 0) { - graph[nz][nx][ny] = 1; - remain--; - queue.offer(new Pos(nx, ny, nz)); - dis[nz][nx][ny] = dis[cp.z][cp.x][cp.y] + 1; - } - } - } - } - - public static void main(String[] args) throws IOException { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - StringTokenizer st = new StringTokenizer(br.readLine()); - m = Integer.parseInt(st.nextToken()); // 열 - n = Integer.parseInt(st.nextToken()); // 행 - h = Integer.parseInt(st.nextToken()); // 높이 - - graph = new int[h][n][m]; - dis = new int[h][n][m]; - - for (int k = 0; k < h; k++) { - for (int i = 0; i < n; i++) { - st = new StringTokenizer(br.readLine()); - for (int j = 0; j < m; j++) { - graph[k][i][j] = Integer.parseInt(st.nextToken()); - if (graph[k][i][j]==0) remain++; - if (graph[k][i][j] == 1) { - queue.offer(new Pos(i, j, k)); - } - } - } - } - BFS(); - - int ans = 0; - for (int k = 0; k < h; k++) { - for (int i = 0; i < n; i++) { - for (int j = 0; j < m; j++) { - ans = Math.max(ans, dis[k][i][j]); - } - } - } - - if (remain >0) { - System.out.println(-1); - } else { - System.out.println(ans); - } - } -} - -class Pos { - int x, y, z; - - public Pos(int x, int y, int z) { - this.x = x; - this.y = y; - this.z = z; - } -} diff --git a/src/week01/jaewon/p1/Main.java b/src/week01/jaewon/p1/Main.java deleted file mode 100644 index 4207a1f..0000000 --- a/src/week01/jaewon/p1/Main.java +++ /dev/null @@ -1,68 +0,0 @@ -import java.io.*; -import java.util.*; - -/* - * 메모리: 14768 kb - * 시간: 112 ms - * - * 0, 0에서 시작해 N - 1, M - 1인 지점까지 BFS 탐색 - */ - -public class Main { - StringBuilder rsb = new StringBuilder(); - int N, K; - boolean[][] table; - boolean[][] visited; - - private void solve() throws Exception { - System.setIn(new FileInputStream("input.txt")); - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - String[] tokens = br.readLine().split(" "); - N = Integer.parseInt(tokens[0]); - K = Integer.parseInt(tokens[1]); - - table = new boolean[N][K]; - visited = new boolean[N][K]; - - for (int i = 0; i < N; ++i) { - String line = br.readLine(); - for (int k = 0; k < K; ++k) { - table[i][k] = line.charAt(k) == '1'; - } - } - System.out.println(bfs()); - } - - int[][] dirs = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } }; - - int bfs() { - Queue q = new LinkedList<>(); - q.add(new int[] { 0, 0, 2 }); // 시작 + 끝 위치 포함한 비용(2) - visited[0][0] = true; - - while (!q.isEmpty()) { - int[] cur = q.poll(); - - for (int[] d : dirs) { - int nextLine = cur[0] + d[0]; - int nextCol = cur[1] + d[1]; - if (nextLine == N - 1 && nextCol == K - 1) { - return cur[2]; - } - if (nextLine < 0 || nextLine >= N || nextCol < 0 || nextCol >= K) - continue; - if (visited[nextLine][nextCol]) - continue; - if (!table[nextLine][nextCol]) - continue; - visited[nextLine][nextCol] = true; - q.add(new int[] { nextLine, nextCol, cur[2] + 1 }); - } - } - return -1; - } - - public static void main(String[] args) throws Exception { - new Main().solve(); - } -} diff --git a/src/week01/jaewon/p2/Main.java b/src/week01/jaewon/p2/Main.java deleted file mode 100644 index 9cac10d..0000000 --- a/src/week01/jaewon/p2/Main.java +++ /dev/null @@ -1,84 +0,0 @@ -import java.io.*; -import java.util.*; - -/** - * 18392 kb - * 136 ms - * - * - 2차원 배열인 table 생성 후 입력 값 저장 (white면 true) - * - 2차원 배열을 순회하며 방문하지 않은 칸이라면 bfs 탐색 - * - 탐색 후 (방문한 칸수)^2를 색상 결과 변수(whiteCnt, blackCnt)에 추가 - */ -public class Main { - StringBuilder rsb = new StringBuilder(); - int N, K; - boolean[][] table; // W is true - boolean[][] visited; - int whiteCnt, blackCnt; - - private void solve() throws Exception { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - String[] tokens = br.readLine().split(" "); - - K = Integer.parseInt(tokens[0]); - N = Integer.parseInt(tokens[1]); - - table = new boolean[N][K]; - visited = new boolean[N][K]; - - for (int i = 0; i < N; ++i) { - String line = br.readLine(); - for (int k = 0; k < K; ++k) { - table[i][k] = line.charAt(k) == 'W'; - } - } - - for (int i = 0; i < N; ++i) { - for (int k = 0; k < K; ++k) { - if (!visited[i][k]) { - int n = bfs(i, k); - if (table[i][k]) { // White - whiteCnt += n * n; - } else { - blackCnt += n * n; - } - } - } - } - System.out.println(whiteCnt + " " + blackCnt); - } - - int[][] dirs = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } }; - - int bfs(int line, int col) { - int cnt = 0; - Queue q = new LinkedList<>(); - q.add(new int[] { line, col }); - - while (!q.isEmpty()) { - int[] cur = q.poll(); - cnt++; - for (int[] d : dirs) { - int nextLine = cur[0] + d[0]; - int nextCol = cur[1] + d[1]; - - if (nextLine < 0 || nextLine >= N || nextCol < 0 || nextCol >= K) - continue; - if (visited[nextLine][nextCol]) - continue; - if (table[nextLine][nextCol] != table[line][col]) - continue; - - visited[nextLine][nextCol] = true; - q.add(new int[] { nextLine, nextCol }); - } - } - if (cnt == 1) // 1 * 1이라면 1 반환 - return 1; - return cnt - 1; - } - - public static void main(String[] args) throws Exception { - new Main().solve(); - } -} diff --git a/src/week01/jaewon/p3/Main.java b/src/week01/jaewon/p3/Main.java deleted file mode 100644 index 197aadd..0000000 --- a/src/week01/jaewon/p3/Main.java +++ /dev/null @@ -1,95 +0,0 @@ -import java.io.*; -import java.util.*; - -/** - * 148016 kb - * 672 ms - * - * - 익은 토마토 위치(line, col, height)를 큐에 저장 - * - 큐에서 하나씩 꺼내며 주변 토마토 상태(동, 서, 남, 북, 윗 칸, 아래 칸)를 익음으로 변경 - * - 새로 익은 토마토는 시간 숫자를 1 늘리고, 큐에 추가 - * - 큐가 비거나(접근 가능한 모든 토마토 순회 완료), - * 다 익을 때까지 반복 - */ - -public class Main { - StringBuilder rsb = new StringBuilder(); - int N, K, H; - - int[][][] tomatoes; - boolean[][][] visited; - - Queue q = new LinkedList<>(); - int greenCnt = 0; // 덜 익은 토마토 개수 - - private void solve() throws Exception { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - - String[] tokens = br.readLine().split(" "); - K = Integer.parseInt(tokens[0]); - N = Integer.parseInt(tokens[1]); - H = Integer.parseInt(tokens[2]); - - tomatoes = new int[H][N][K]; - visited = new boolean[H][N][K]; - - for (int h = 0; h < H; ++h) { - for (int i = 0; i < N; ++i) { - tokens = br.readLine().split(" "); - for (int k = 0; k < K; ++k) { - tomatoes[h][i][k] = Integer.parseInt(tokens[k]); - if (tomatoes[h][i][k] == 0) { - greenCnt++; - } else if (tomatoes[h][i][k] == 1) { - q.add(new int[] { i, k, h, 0 }); - } - } - } - } - - int currentT = 0; - - while (greenCnt > 0) { - while (!q.isEmpty() && q.peek()[3] == currentT) { - changeNearby(); - } - if (q.isEmpty() && greenCnt > 0) { - System.out.println(-1); - return; - } - currentT++; - } - - System.out.println(currentT); - } - - // line, col, h - int[][] dirs = { { 1, 0, 0 }, { 0, 1, 0 }, { -1, 0, 0 }, { 0, -1, 0 }, { 0, 0, 1 }, { 0, 0, -1 } }; - - void changeNearby() { - if (q.isEmpty()) - return; - - int[] cur = q.poll(); - for (int[] d : dirs) { - int nextLine = cur[0] + d[0]; - int nextCol = cur[1] + d[1]; - int nextHeight = cur[2] + d[2]; - - if (nextLine < 0 || nextLine >= N || nextCol < 0 || nextCol >= K || nextHeight < 0 || nextHeight >= H) - continue; - if (visited[nextHeight][nextLine][nextCol]) - continue; - if (tomatoes[nextHeight][nextLine][nextCol] != 0) - continue; - visited[nextHeight][nextLine][nextCol] = true; - tomatoes[nextHeight][nextLine][nextCol] = 1; // change tomato - greenCnt--; - q.add(new int[] { nextLine, nextCol, nextHeight, cur[3] + 1 }); - } - } - - public static void main(String[] args) throws Exception { - new Main().solve(); - } -} diff --git a/src/week01/sungHee/p1/p1_SungHee.java b/src/week01/sungHee/p1/p1_SungHee.java deleted file mode 100644 index af554e3..0000000 --- a/src/week01/sungHee/p1/p1_SungHee.java +++ /dev/null @@ -1,90 +0,0 @@ -package week01.sungHee.p1; - -import java.io.*; -import java.util.*; - -/** - * 문제 링크 : https://www.acmicpc.net/problem/2178 - * 메모리 : 12304 KM - * 시간 : 76 ms - */ - -/** - * 적용 알고리즘 : BFS(최단 경로를 찾는 문제) - * - * miro[y][x]의 값을 depth로 생각 - * miro[0][0]을 2로 설정하여 - * miro[y][x]의 값이 1인 경우에만 지나갈 수 있다. - * (0이면 못지나가는 칸, 1초과면 이미 지나간 칸) - */ - -public class p1_SungHee { - - static int[][] miro; - static int N, M; - static boolean[][] visited; - - static int[] dx = {1, 0, -1, 0}; //x방향배열 - static int[] dy = {0, -1, 0, 1}; //y방향배열 - - private static class State { - public final int y; - public final int x; - - public State(int y, int x) { - this.y = y; - this.x = x; - } - } - - - public static void main(String[] args) throws IOException { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - StringTokenizer st = new StringTokenizer(br.readLine()); - - N = Integer.parseInt(st.nextToken()); - M = Integer.parseInt(st.nextToken()); - - miro = new int[N][M]; - - for (int i = 0; i < N; i++) { - String line = br.readLine(); - for(int j =0; j queue = new LinkedList<>(); - queue.offer(new State(y, x)); - - while (!queue.isEmpty()) { - State cur = queue.poll(); - - //방향 탐색 - for (int i = 0; i < 4; i++) { - int nx = cur.x + dx[i]; - int ny = cur.y + dy[i]; - - //범위 확인 - if (nx < 0 || ny < 0 || nx >= M || ny >= N) { - continue; - } - - //조건 확인 후 큐에 추가 - if(miro[ny][nx] == 1) { - miro[ny][nx] = miro[cur.y][cur.x] +1; - queue.offer(new State(ny, nx)); - } - } - - } - } -} diff --git a/src/week01/sungHee/p2/p2_SungHee.java b/src/week01/sungHee/p2/p2_SungHee.java deleted file mode 100644 index e20c890..0000000 --- a/src/week01/sungHee/p2/p2_SungHee.java +++ /dev/null @@ -1,87 +0,0 @@ -package week01.sungHee.p2; - -import java.io.*; -import java.util.*; - -/** - * 문제 링크 : https://www.acmicpc.net/problem/1303 - * 메모리 : 11852 KM - * 시간 : 72 ms - * - * 풀이 - * DFS(같은 부류를 찾는 문제) 사용 - * 가로가 N, 세로가 M 확인!! - * - * 방문 여부는 배열의 문자로 구분(방문했으면 'V'로 변환) - * 0,0 부터 배열 방문 - * W, M 기준을 dfs 호출 - * dfs 호출 시 어떤 팀을 나타내는지 팀 문자를 인자로 같이 넘김 - * 하나의 dfs가 끝나면 cnt(뭉쳐있는 인원수) 제곱 후 각 팀의 병사의 위력에 더함 - */ - -public class p2_SungHee { - - static int[] dx = { 1, 0, -1, 0 }; // x방향배열 - static int[] dy = { 0, -1, 0, 1 }; // y방향배열 - - static char map[][]; - - static int N, M; - static int w, b; // 병사 위력의 합 - - static int cnt; - - private static void dfs(int y, int x, char team) { - for (int i = 0; i < 4; i++) { - int ny = y + dy[i]; - int nx = x + dx[i]; - - if(nx < 0 || nx >= N || ny < 0 || ny >= M) continue; - if(map[ny][nx] != team) continue; - - map[ny][nx] = 'V'; // 방문 표기 - cnt++; - dfs(ny, nx, team); - } - - } - - public static void main(String[] args) throws IOException { - // setting - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - StringTokenizer st = new StringTokenizer(br.readLine()); - - N = Integer.parseInt(st.nextToken()); - M = Integer.parseInt(st.nextToken()); - - map = new char[M][N]; - - for (int i = 0; i < M; i++) { - String line = br.readLine(); - for (int j = 0; j < N; j++) { - map[i][j] = line.charAt(j); - } - } - - // dfs - for (int i = 0; i < M; i++) { - for (int j = 0; j < N; j++) { - cnt = 1; // cnt 초기화 - - if (map[i][j] == 'W') { - // visited - map[i][j] = 'V'; - dfs(i, j, 'W'); - w += (cnt * cnt); - } - if (map[i][j] == 'B') { - map[i][j] = 'V'; - dfs(i, j, 'B'); - b += (cnt * cnt); - } - } - } - - System.out.println(w + " " + b); - } -} diff --git a/src/week01/sungHee/p3/p3_SungHee.java b/src/week01/sungHee/p3/p3_SungHee.java deleted file mode 100644 index b798b5d..0000000 --- a/src/week01/sungHee/p3/p3_SungHee.java +++ /dev/null @@ -1,110 +0,0 @@ -package week01.sungHee.p3; - -import java.util.*; -import java.io.*; - -/** - * 문제 링크 : https://www.acmicpc.net/problem/7569 - * 메모리 : 121148 KM - * 시간 : 552ms - * - * 풀이 - * - 최소 일수구하는 문제 -> BFS 사용 - * - * 익은 토마토의 위치를 queue에 저장함 - * bfs - * 1. queue에서 익은 토마토 꺼냄 - * 2. 위(z방향), 아래(z방향), 상(y방향), 하(y방향), 좌, 우 방향을 돌며 - * 3. 익을 수 있는 토마토가 있는지 확인(0인경우) - * 4. 익을 수 있는 토마토면 - * 4-1. queue에 저장 - * 4-2. box에 이전 위치의 box값 + 1로 저장 (날짜 확인 위해) - * 5. 1~4의 과정을 queue가 비워질 때 까지 반복(익을 수 있는 토마토가 다 익을 때까지) - * - * 6. 날짜 출력 - * - */ - -public class p3_SungHee { - - static int dz[] = {1, -1, 0, 0, 0, 0}; // z방향배열 - static int dy[] = {0, 0, 0, 0, 1, -1}; // y방향배열 - static int dx[] = {0, 0, 1, -1, 0, 0}; // x방향배열 - - static int box[][][]; - - static int N, M, H; - - static Queue ripeApplesQueue; //익은 사과 큐 - - private static class Apple { - public final int z; - public final int y; - public final int x; - - public Apple(int z, int y, int x) { - this.z = z; - this.y = y; - this.x = x; - } - } - - - public static void main(String[] args) throws IOException{ - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - StringTokenizer st = new StringTokenizer(br.readLine()); - - M = Integer.parseInt(st.nextToken()); - N = Integer.parseInt(st.nextToken()); - H = Integer.parseInt(st.nextToken()); - - box = new int[H][N][M]; - ripeApplesQueue = new LinkedList<>(); - - for(int i = 0; i < H; i++) { - for(int j = 0; j < N; j++) { - st = new StringTokenizer(br.readLine()); - for(int k=0; k < M; k++) { - box[i][j][k] = Integer.parseInt(st.nextToken()); - if (box[i][j][k] == 1) ripeApplesQueue.offer(new Apple(i, j, k)); - } - } - } - - bfs(); - System.out.println(findDay()); - } - - static void bfs() { - while (!ripeApplesQueue.isEmpty()) { - Apple cur = ripeApplesQueue.poll(); - - for(int i = 0; i < 6; i++) { - int nz = cur.z + dz[i]; - int ny = cur.y + dy[i]; - int nx = cur.x + dx[i]; - - // 익을 수 있는지 체크 - if (nz < 0 || nx < 0 || ny <0 || nz >= H || ny >= N || nx >= M || box[nz][ny][nx] != 0 ) continue; - - box[nz][ny][nx] = box[cur.z][cur.y][cur.x] + 1; - ripeApplesQueue.offer(new Apple(nz, ny, nx)); - } - } - - } - - static int findDay() { - // box에 하나라도 0이 있으면 -1 출력 - int result = 0; - for(int i = 0; i < H; i++) { - for(int j = 0; j < N; j++) { - for(int k=0; k < M; k++) { - if (box[i][j][k] == 0) return -1; - result = Math.max(result, box[i][j][k]); - } - } - } - return result -1; - } -} diff --git a/src/week02/gahyun/p1/Main.java b/src/week02/gahyun/p1/Main.java deleted file mode 100644 index da99624..0000000 --- a/src/week02/gahyun/p1/Main.java +++ /dev/null @@ -1,45 +0,0 @@ -package week02.gahyun.p1; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.List; -import java.util.StringTokenizer; - -/* - * 문제 링크 : https://www.acmicpc.net/problem/1138 - * 메모리 : 14228 KM - * 시간 : 100 ms - */ -/* - 배열 요소 역순으로 리스트에 삽입 - arr[i] = 인덱스 - i = 키 - */ -public class Main { - public static void main(String[] args) throws IOException { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - int N = Integer.parseInt(br.readLine()); - List answer = new ArrayList<>(); - int[] arr = new int[N]; - StringTokenizer st = new StringTokenizer(br.readLine()); - StringBuilder sb = new StringBuilder(); - - // 입력 받기 - for (int i = 1; i < N; i++) { - arr[i] = Integer.parseInt(st.nextToken()); - } - - answer.add(N); // 최초 삽입 - for (int i = N - 1; i > 0; i--) { - answer.add(arr[i], i); - } - - // 출력 - for (Integer x : answer) { - sb.append(x).append(" "); - } - System.out.println(sb); - } -} diff --git a/src/week02/gahyun/p2/Main.java b/src/week02/gahyun/p2/Main.java deleted file mode 100644 index 4068b46..0000000 --- a/src/week02/gahyun/p2/Main.java +++ /dev/null @@ -1,77 +0,0 @@ -package week02.gahyun.p2; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.LinkedList; -import java.util.Queue; -import java.util.StringTokenizer; - -/* - * 문제 링크 : https://www.acmicpc.net/problem/7562 - * 메모리 : 72724 KM - * 시간 : 268 ms - */ -/* - 최단 경로 -> BFS - 각 레벨이 이동 횟수 - */ - -public class Main { - static int n, x1, x2, y1, y2; - static int[][] graph; - static int[] dx = {-1, 1, 2, 2, 1, -1, -2, -2}; - static int[] dy = {-2, -2, -1, 1, 2, 2, 1, -1}; - - public static void main(String[] args) throws IOException { - int tries; - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - tries = Integer.parseInt(br.readLine()); - StringTokenizer st; - for (int i = 0; i < tries; i++) { - n = Integer.parseInt(br.readLine()); - - st = new StringTokenizer(br.readLine()); - x1 = Integer.parseInt(st.nextToken()); - y1 = Integer.parseInt(st.nextToken()); - - st = new StringTokenizer(br.readLine()); - x2 = Integer.parseInt(st.nextToken()); - y2 = Integer.parseInt(st.nextToken()); - - BFS(); - System.out.println(graph[y2][x2]); // 목표 지점 레벨 - } - } - - public static void BFS() { - boolean[][] visited = new boolean[n][n]; - graph = new int[n][n]; - Queue queue = new LinkedList<>(); - queue.offer(new Pos(x1, y1)); - visited[y1][x1] = true; - while (!queue.isEmpty()) { - Pos cp = queue.remove(); - for (int i = 0; i < 8; i++) { - int nx = cp.x + dx[i]; - int ny = cp.y + dy[i]; - if (nx >= 0 && ny >= 0 && nx < n && ny < n && !visited[ny][nx]) { - queue.offer(new Pos(nx, ny)); - visited[ny][nx] = true; - graph[ny][nx] = graph[cp.y][cp.x] + 1; - } - if (graph[y2][x2]!=0) return; // 목표 지점 도착 시 종료 -> 메모리 절약 - } - - } - } -} - -class Pos { - int x, y; - - Pos(int x, int y) { - this.x = x; - this.y = y; - } -} diff --git a/src/week02/gahyun/p3/Main.java b/src/week02/gahyun/p3/Main.java deleted file mode 100644 index 7517038..0000000 --- a/src/week02/gahyun/p3/Main.java +++ /dev/null @@ -1,58 +0,0 @@ -package week02.gahyun.p3; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.StringTokenizer; - -/* - * 문제 링크 : https://www.acmicpc.net/problem/19951 - * 메모리 : 62536 KM - * 시간 : 576 ms - */ - -/* -누적합 -1 2 3 4 5 주어진 배열 -1 4 2 - -2 0 0 0 -2 0 -2 2 2 2 0 0 누적합 -3 4 5 6 4 5 결과 -a에 k, b+1에 -k 저장하고 1부터 누적합 구하기 -마지막에 누적합 기존 배열에 더하기 - */ -public class Main { - public static void main(String[] args) throws IOException { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - StringTokenizer st = new StringTokenizer(br.readLine()); - StringBuilder sb = new StringBuilder(); - - int N = Integer.parseInt(st.nextToken()); - int M = Integer.parseInt(st.nextToken()); - - int[] arr = new int[N + 1]; // 1부터 - int[] order = new int[N + 2]; - - st = new StringTokenizer(br.readLine()); - for (int i = 1; i <= N; i++) { - arr[i] = Integer.parseInt(st.nextToken()); - } - - for (int i = 0; i < M; i++) { - st = new StringTokenizer(br.readLine()); - int a = Integer.parseInt(st.nextToken()); - int b = Integer.parseInt(st.nextToken()); - int k = Integer.parseInt(st.nextToken()); - - order[a] += k; - order[b + 1] -= k; - } - - for (int i = 1; i <= N; i++) { - order[i] += order[i - 1]; - sb.append(arr[i] + order[i]).append(" "); - } - System.out.println(sb); - } -} \ No newline at end of file diff --git a/src/week02/jaewon/p1/Main.java b/src/week02/jaewon/p1/Main.java deleted file mode 100644 index bac77af..0000000 --- a/src/week02/jaewon/p1/Main.java +++ /dev/null @@ -1,41 +0,0 @@ -import java.io.*; -import java.util.*; - -/* - * 문제 링크 : https://www.acmicpc.net/problem/1138 - * 메모리 : 15860 kb - * 시간 : 144 ms - */ -/* - 주어진 배열의 값이 큰 사람이 왼쪽에 몇 명인지 의미 - 빈 자리 띄우고 왼쪽부터 오른쪽으로 채우기 -*/ - -public class Main { - private void sol() throws Exception { - // System.setIn(new FileInputStream("input.txt")); - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - - int N = Integer.parseInt(br.readLine()); - - String[] tokens = br.readLine().split(" "); - int[] res = new int[N]; - for (int i = 0; i < N; ++i) { - int num = Integer.parseInt(tokens[i]); - for (int k = 0; k < N; ++k) { - if (num == 0 && res[k] == 0) { - res[k] = i + 1; - break; - } else if (res[k] == 0) - num--; - } - } - for (int i = 0; i < N; ++i) { - System.out.print(res[i] + " "); - } - } - - public static void main(String[] args) throws Exception { - new Main().sol(); - } -} diff --git a/src/week02/jaewon/p2/Main.java b/src/week02/jaewon/p2/Main.java deleted file mode 100644 index 448a403..0000000 --- a/src/week02/jaewon/p2/Main.java +++ /dev/null @@ -1,64 +0,0 @@ -import java.io.*; -import java.util.*; - -/* - * 문제 링크 : https://www.acmicpc.net/problem/7562 - * 메모리 : 73652 kb - * 시간 : 268 ms -*/ -/* - BFS, 한점에서 다른 점으로 이동하는 최단 횟수 - */ - -public class Main { - int N; - int l, c, tL, tC; - - void solve() throws Exception { - System.setIn(new FileInputStream("input.txt")); - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - int T = Integer.parseInt(br.readLine()); - while (T-- > 0) { - N = Integer.parseInt(br.readLine()); - String[] tokens = br.readLine().split(" "); - l = Integer.parseInt(tokens[0]); - c = Integer.parseInt(tokens[1]); - tokens = br.readLine().split(" "); - tL = Integer.parseInt(tokens[0]); - tC = Integer.parseInt(tokens[1]); - System.out.println(bfs()); - } - } - - int bfs() { - Queue q = new LinkedList<>(); - boolean[][] visited = new boolean[N][N]; - q.add(new int[] { l, c, 0 }); - while (!q.isEmpty()) { - int[] cur = q.poll(); - if (cur[0] == tL && cur[1] == tC) { - return cur[2]; - } - for (int[] d : dirs) { - int nl = cur[0] + d[0]; - int nc = cur[1] + d[1]; - if (nl < 0 || nl >= N || nc < 0 || nc >= N) - continue; - if (visited[nl][nc]) - continue; - - q.add(new int[] { nl, nc, cur[2] + 1 }); - visited[nl][nc] = true; - } - } - return -1; - } - - int[][] dirs = { - { -1, -2 }, { 1, -2 }, { 2, -1 }, { 2, 1 }, { 1, 2 }, { -1, 2 }, { -2, 1 }, { -2, -1 } - }; - - public static void main(String[] args) throws Exception { - new Main().solve(); - } -} diff --git a/src/week02/jaewon/p3/Main.java b/src/week02/jaewon/p3/Main.java deleted file mode 100644 index 31cdf77..0000000 --- a/src/week02/jaewon/p3/Main.java +++ /dev/null @@ -1,58 +0,0 @@ -import java.io.*; -import java.util.*; - -/* - * 문제 링크 : https://www.acmicpc.net/problem/19951 - * 메모리 : 67192 kb - * 시간 : 656 ms -*/ -/* - 누적합, start부터 변화된 값을 따라서 누적된 값을 사용 - end + 1부터는 누적값을 0으로 초기화 (end + 1 부터는 변화 X) - */ - -public class Main { - BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); - int N, K; - int[] arr, deltas; - - private void sol() throws Exception { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - String[] tokens = br.readLine().split(" "); - - N = Integer.parseInt(tokens[0]); - K = Integer.parseInt(tokens[1]); - arr = new int[N + 1]; - - tokens = br.readLine().split(" "); - for (int i = 1; i <= N; ++i) { - arr[i] = Integer.parseInt(tokens[i - 1]); - } - - deltas = new int[N + 1]; - for (int i = 0; i < K; ++i) { - tokens = br.readLine().split(" "); - int s = Integer.parseInt(tokens[0]); - int e = Integer.parseInt(tokens[1]); - int k = Integer.parseInt(tokens[2]); - alterDirt(s, e, k); - } - - for (int i = 1; i <= N; ++i) { - deltas[i] = deltas[i - 1] + deltas[i]; - arr[i] += deltas[i]; - bw.append(arr[i] + " "); - } - } - - // end 포함 O - void alterDirt(int start, int end, int delta) { - deltas[start] += delta; - if (end != N) - deltas[end + 1] -= delta; - } - - public static void main(String[] args) throws Exception { - new Main().sol(); - } -} diff --git a/src/week02/sunghee/p1/Main.java b/src/week02/sunghee/p1/Main.java deleted file mode 100644 index 692d576..0000000 --- a/src/week02/sunghee/p1/Main.java +++ /dev/null @@ -1,45 +0,0 @@ -package week02.sunghee.p1; - -import java.io.*; -import java.util.*; - -/** - * 문제 링크 : https://www.acmicpc.net/problem/1138 - * 메모리 : 11596 KM - * 시간 : 68 ms - */ - -/** - * arr에 값 받기 - * 키가 가장 큰 순부터 for문 돌기 - * ArrayList에 왼쪽에 키가 큰 사람 수를 index로 하여 추가 - */ - -public class Main { - private void solve() throws IOException { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - int N = Integer.parseInt(br.readLine()); - - StringTokenizer st = new StringTokenizer(br.readLine()); - int[] arr = new int[N]; - for(int i = 0; i < N; i++) { - arr[i] = Integer.parseInt(st.nextToken()); - } - - List resultList = new ArrayList<>(); - for(int i = N; i > 0 ; i--) { - resultList.add(arr[i-1], i); - } - - StringBuilder sb = new StringBuilder(); - for(Integer p : resultList) { - sb.append(p + " "); - } - - System.out.println(sb.toString().trim()); - } - - public static void main(String[] args) throws IOException { - new Main().solve(); - } -} \ No newline at end of file diff --git a/src/week02/sunghee/p2/Main.java b/src/week02/sunghee/p2/Main.java deleted file mode 100644 index b451e76..0000000 --- a/src/week02/sunghee/p2/Main.java +++ /dev/null @@ -1,81 +0,0 @@ -package week02.sunghee.p2; - -import java.io.*; -import java.util.*; - -/** - * 문제 링크 : https://www.acmicpc.net/problem/7562 - * 메모리 : 68976 KM - * 시간 : 212 ms - */ - -/** - * chess에 depth값 저장하여 출력 - * - * 테스트 케이스 for문 돌기 - * fromY, fromX, toY, toX 값 받아 bfs에 인자값으로 넘겨줌 - * bfs - * 1. 시작 좌표을 큐에 넣어주고 chess[fromY][fromX] = 1; - * 2. 큐가 빌때 까지 반복 - * 2-1. 이동 방향 도안 for문 돌기 - * 2-2. 다음 방향이 접합한지 판단 - * 2-3. 적합하면 depth 값 1 올려서 chess 해당 좌표에 저장 - * 2-4. 해당 좌표가 이동하려는 좌표 값이면 retrun, 아니면 큐에 저장 - */ - -public class Main { - - int[][] dir = { { 2, -1 }, { -2, -1 }, { 1, -2 }, { -1, -2 }, { 2, 1,}, { 1, 2 }, { -1, 2 }, { -2, 1 } }; - int[][] chess; - - int I; - - private void solve() throws IOException { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - int T = Integer.parseInt(br.readLine()); - - for (int testCase = 0; testCase < T; testCase++) { - I = Integer.parseInt(br.readLine()); - StringTokenizer st = new StringTokenizer(br.readLine()); - int fromY = Integer.parseInt(st.nextToken()); - int fromX = Integer.parseInt(st.nextToken()); - - st = new StringTokenizer(br.readLine()); - int toY = Integer.parseInt(st.nextToken()); - int toX = Integer.parseInt(st.nextToken()); - - chess = new int[I][I]; - - bfs(fromY, fromX, toY, toX); - - System.out.println(chess[toY][toX] -1); - } - } - - private void bfs(int fromY, int fromX, int toY, int toX) { - Queue q = new LinkedList<>(); - chess[fromY][fromX] = 1; - q.offer(new int[]{fromY, fromX}); - - while(!q.isEmpty()) { - int[] cur = q.poll(); - - for(int[] movePoint : dir) { - int ny = cur[0] + movePoint[0]; - int nx = cur[1] + movePoint[1]; - - if (ny < 0 || ny >= I || nx < 0 || nx >= I || chess[ny][nx] != 0) continue; - chess[ny][nx] = chess[cur[0]][cur[1]] + 1; - if (ny == toY && nx == toX) return; - - q.offer(new int[]{ny, nx}); - } - } - } - - - public static void main(String[] args) throws IOException { - new Main().solve(); - } -} - diff --git a/src/week02/sunghee/p3/Main.java b/src/week02/sunghee/p3/Main.java deleted file mode 100644 index 987e873..0000000 --- a/src/week02/sunghee/p3/Main.java +++ /dev/null @@ -1,66 +0,0 @@ -package week02.sunghee.p3; - -import java.io.*; -import java.util.*; - -/** - * 문제 링크 : https://www.acmicpc.net/problem/19951 - * 메모리 : 63416KM - * 시간 : 472ms - */ - -/** - * 조교 지시의 처음과 끝만 저장한 후 누적합 + dp로 풀기 - * - * height가 1부터 시작으로 크기를 N+1로 잡음 - * 누적 합 배열(prefixSum)는 N+2 크기로 설정 - * 지시 상항의 시작인덱스(start)인 prefixSum값에 k값을 더하고 - * 끝인덱스(end)인 prefixSum값에 k값을 빼준다. - * - * 이후 prefixSum을 돌면서 - * prefixSum[i] = prefixSum[i-1] + prefixSum[i] (점화식)을 진행하고 - * height의 값과 더해서 연병장 각 칸의 높이을 구한다. - */ - -public class Main { - - private void solve() throws IOException { - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - StringTokenizer st = new StringTokenizer(br.readLine()); - - int N = Integer.parseInt(st.nextToken()); - int M = Integer.parseInt(st.nextToken()); - - int[] height = new int[N+1]; - - st = new StringTokenizer(br.readLine()); - for (int i = 1; i < N+1; i++) { - height[i] = Integer.parseInt(st.nextToken()); - } - - int[] prefixSum = new int[N+2]; - for(int i = 0; i < M; i++) { - st = new StringTokenizer(br.readLine()); - int start = Integer.parseInt(st.nextToken()); - int end = Integer.parseInt(st.nextToken()); - int k = Integer.parseInt(st.nextToken()); - - prefixSum[start] += k; - prefixSum[end + 1] -= k; - } - - - StringBuilder sb = new StringBuilder(); - for (int i = 1; i < N + 1; i++) { - prefixSum[i] = prefixSum[i - 1] + prefixSum[i]; - sb.append(height[i]+prefixSum[i]).append(" "); - } - - System.out.println(sb); - } - - public static void main(String[] args) throws IOException { - new Main().solve(); - } -} - diff --git a/src/week03/gahyun/p1/Main.java b/src/week03/gahyun/p1/Main.java deleted file mode 100644 index 5d91778..0000000 --- a/src/week03/gahyun/p1/Main.java +++ /dev/null @@ -1,48 +0,0 @@ -package week03.gahyun.p1; -import java.util.Arrays; - -/** - * 문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/42840 - * 메모리 : 79.4 MB - * 시간 : 15.46 ms - */ - -/** - * 학생별 찍는 번호 배열에 저장 - * 정답 인덱스 % 각 배열 길이 -> 정답 횟수 세기 - * cnt 배열 순회해서 최고점수와 cnt 요소 비교 -> 인덱스 + 1이 최고 득점자 - */ - -class Solution { - public int[] solution(int[] answers) { - int[] s1 = {1,2,3,4,5}; // 찍는 번호 - int[] s2 = {2,1,2,3,2,4,2,5}; - int[] s3 = {3,3,1,1,2,2,4,4,5,5}; - int[] cnt = new int[3]; // 맞춘 횟수 - - // 맞춘 횟수 세기 - for (int i=0;i < answers.length;i++){ - if (s1[i%s1.length]==answers[i]) cnt[0]++; - if (s2[i%s2.length]==answers[i]) cnt[1]++; - if (s3[i%s3.length]==answers[i]) cnt[2]++; - } - - // 최다득점자 구하기 - String max_s_str = ""; - int max = Arrays.stream(cnt).max().getAsInt(); //최고 점수 - - for (int i=0;i int[] - int[] answer = new int[max_s_str.length()]; - int answerInd=0; - for (char ind : max_s_str.toCharArray()){ - answer[answerInd++] += ind-'0'; - } - return answer; - } -} \ No newline at end of file diff --git a/src/week03/gahyun/p2/Main.java b/src/week03/gahyun/p2/Main.java deleted file mode 100644 index 11ebeb3..0000000 --- a/src/week03/gahyun/p2/Main.java +++ /dev/null @@ -1,31 +0,0 @@ -package week03.gahyun.p2; - -/** - * 문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/43165 - * 메모리 : 75.2MB - * 시간 : 4.52ms - */ - -/** - * DFS - * 값 +- 여부로 분기처리되는 트리 형태 (->전위순회) - * 각 레벨 진행될 때마다 배열값 더하거나 뺌 - * 리프 노드에서 총합이 타겟 넘버면 카운트 증가 - */ -class Solution { - static int answer = 0; - public int solution(int[] numbers, int target) { - DFS(0, 0, numbers, target); - return answer; - } - public static void DFS(int lv, int total, int[] arr, int target){ - if (lv==arr.length){ - if (total==target) { - answer++; - } - } else { - DFS(lv+1, total+arr[lv], arr, target); - DFS(lv+1, total-arr[lv], arr, target); - } - } -} diff --git a/src/week03/gahyun/p3/Main.java b/src/week03/gahyun/p3/Main.java deleted file mode 100644 index b58e6b5..0000000 --- a/src/week03/gahyun/p3/Main.java +++ /dev/null @@ -1,45 +0,0 @@ -package week03.gahyun.p3; - -import java.util.*; - -/** - * 문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/43162 - * 메모리 : 81.1MB - * 시간 : 0.54ms - */ - -/** - * 방문 안한 그래프 BFS 탐색 - * 탐색 마친 후 네트워크 수 증가시키기 - * 인접행렬 computers[i][i]도 1로 표시되므로 방문 시 제외해야 함 - */ -class Solution { - static boolean[] visited; - public int solution(int n, int[][] computers) { - int answer = 0; - visited = new boolean[n]; - for (int i=0;i que = new LinkedList<>(); - que.offer(v); - visited[v] = true; - while (!que.isEmpty()){ - int cur = que.poll(); - for (int i = 0;i answerList = new ArrayList<>(); - - for (int i = 0; i < counts.length; i++) { - if (counts[i] == maxCount) { - answerList.add(i + 1); - } - } - - return answerList.stream().mapToInt(i -> i).toArray(); - } -} diff --git a/src/week03/jaewon/p2/Solution.java b/src/week03/jaewon/p2/Solution.java deleted file mode 100644 index bbf003b..0000000 --- a/src/week03/jaewon/p2/Solution.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/43165 - * DFS로 탐색하며 target 수가 될 수 있는 경우의 수를 더함 -*/ - -class Solution { - private int N; - private int[] numbers; - private int target; - private int count = 0; - - private void dfs(int index, int sum) { - if (index == N) { - if (sum == target) { - count++; - } - return; - } - dfs(index + 1, sum + numbers[index]); - dfs(index + 1, sum - numbers[index]); - } - - public int solution(int[] numbers, int target) { - this.numbers = numbers; - this.target = target; - N = numbers.length; - dfs(0, 0); - return count; - } -} diff --git a/src/week03/jaewon/p3/Solution.java b/src/week03/jaewon/p3/Solution.java deleted file mode 100644 index b7e4ba7..0000000 --- a/src/week03/jaewon/p3/Solution.java +++ /dev/null @@ -1,41 +0,0 @@ -import java.util.*; - -/* - * 문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/43162 - * 그래프를 BFS로 순회하며 연결 여부 확인 - * 방문 여부를 확인하며 새로 방문하는 경우에 네트워크의 개수를 1 증가 -*/ - -public class Solution { - boolean[] visited = new boolean[202]; - int cnt = 0; - - public void bfs(int start, int n, int[][] computers) { - Queue q = new LinkedList<>(); - q.add(start); - visited[start] = true; - - while (!q.isEmpty()) { - int node = q.poll(); - - for (int i = 0; i < n; ++i) { - if (visited[i]) - continue; - if (computers[node][i] == 0 || node == i) - continue; - visited[i] = true; - q.add(i); - } - } - } - - public int solution(int n, int[][] computers) { - for (int i = 0; i < n; ++i) { - if (!visited[i]) { - cnt++; - bfs(i, n, computers); - } - } - return cnt; - } -} diff --git a/src/week03/sunghee/p1/Solution.java b/src/week03/sunghee/p1/Solution.java deleted file mode 100644 index 1864f38..0000000 --- a/src/week03/sunghee/p1/Solution.java +++ /dev/null @@ -1,63 +0,0 @@ -package week03.sunghee.p1; - -import java.util.*; -import java.util.stream.IntStream; - -/** - * 문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/42840 - * 테스트 1 〉(4.13ms, 78.3MB) - * 테스트 2 〉(4.81ms, 82.2MB) - * 테스트 3 〉(11.37ms, 75MB) - * 테스트 4 〉(6.62ms, 79.3MB) - * 테스트 5 〉(5.00ms, 72.9MB) - * 테스트 6 〉(3.27ms, 76.6MB) - * 테스트 7 〉(6.22ms, 82.1MB) - * 테스트 8 〉(3.22ms, 74.3MB) - * 테스트 9 〉(4.02ms, 68.5MB) - * 테스트 10 〉(4.23ms, 77.2MB) - * 테스트 11 〉(4.33ms, 77.6MB) - * 테스트 12 〉(5.04ms, 79.7MB) - * 테스트 13 〉(4.27ms, 78.5MB) - * 테스트 14 〉(4.14ms, 81.6MB) - */ - -/** - * 각 수포자의 반복되는 규칙을 randomAnswers에 저장 - * answers의 길이만큼 반복해서 각 문제별 각 수포자가 해당 문제 정답을 맞췄는지 확인 - * 각 수포자의 정답은 randomAnswers에 저장된 각자의 크기의 나머지로 확인하고 - * 정답과 같으면 score++ - * 각 수포자의 score의 최대 값을 확인하고 - * 최대값과 같은 수포자의 번호를 리턴 - */ - -public class Solution { - - public int[] solution(int[] answers) { - - int[][] randomAnswers = { - {1, 2, 3, 4, 5}, - {2, 1, 2, 3, 2, 4, 2, 5}, - {3, 3, 1, 1, 2, 2, 4, 4, 5, 5} - }; - - int[] score = new int[3]; - - for(int i = 0; i < answers.length; i++) { - if (randomAnswers[0][i % 5] == answers[i]) score[0]++; - if (randomAnswers[1][i % 8] == answers[i]) score[1]++; - if (randomAnswers[2][i % 10] == answers[i]) score[2]++; - } - - int maxScore = Math.max(score[0], Math.max(score[1], score[2])); - - return IntStream.range(0, 3) - .filter(i -> score[i] == maxScore) - .map(i -> i + 1).toArray(); - } - - - public static void main(String[] args) { - System.out.println(Arrays.toString(new Solution().solution(new int[]{1,2,3,4,5}))); - System.out.println(Arrays.toString(new Solution().solution(new int[]{1,3,2,4,2}))); - } -} diff --git a/src/week03/sunghee/p2/Solution.java b/src/week03/sunghee/p2/Solution.java deleted file mode 100644 index 67854c9..0000000 --- a/src/week03/sunghee/p2/Solution.java +++ /dev/null @@ -1,45 +0,0 @@ -package week03.sunghee.p2; - - -/** - * 문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/431650 - *테스트 1 〉 (4.33ms, 77.6MB) - *테스트 2 〉 (6.52ms, 78.6MB) - *테스트 3 〉 (0.18ms, 74.6MB) - *테스트 4 〉 (0.34ms, 74.9MB) - *테스트 5 〉 (0.67ms, 73.5MB) - *테스트 6 〉 (0.32ms, 74.2MB) - *테스트 7 〉 (0.22ms, 77MB) - *테스트 8 〉 (0.42ms, 74.3MB) - */ - -/** - * dfs 구현 - * depth가 numbers 길이와 같을 때 종료 - * sum과 target이 같으면 1, 다르면 0을 반환 - * numbers의 값을 더할 경우와 뺄 경우로 나눠서 dfs 각각 호출 - * 각각의 경우의 리턴 값을 더해서 리턴 - */ - -public class Solution { - public int solution(int[] numbers, int target) { - return dfs(numbers, target, 0, 0); - } - - private int dfs(int[] numbers, int target, int depth, int sum) { - if(depth == numbers.length) { - if(sum == target) { - return 1; - } - return 0; - } - - return dfs(numbers, target, depth + 1, sum + numbers[depth]) + - dfs(numbers, target, depth + 1,sum - numbers[depth]); - } - - public static void main(String[] args) { - System.out.println(new Solution().solution(new int[]{1, 1, 1, 1, 1}, 3)); - System.out.println(new Solution().solution(new int[]{4, 1, 2, 1}, 4)); - } -} diff --git a/src/week03/sunghee/p3/Solution.java b/src/week03/sunghee/p3/Solution.java deleted file mode 100644 index e36e84d..0000000 --- a/src/week03/sunghee/p3/Solution.java +++ /dev/null @@ -1,72 +0,0 @@ -package week03.sunghee.p3; - -/** - * 문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/43162 - * - *테스트 1 〉 (0.02ms, 69.3MB) - *테스트 2 〉 (0.02ms, 76.5MB) - *테스트 3 〉 (0.03ms, 75.5MB) - *테스트 4 〉 (0.03ms, 71.9MB) - *테스트 5 〉 (0.01ms, 72.9MB) - *테스트 6 〉 (0.11ms, 74.3MB) - *테스트 7 〉 (0.03ms, 73.2MB) - *테스트 8 〉 (0.09ms, 73.2MB) - *테스트 9 〉 (0.04ms, 70.5MB) - *테스트 10 〉 (0.04ms, 74.8MB) - *테스트 11 〉 (0.32ms, 84.6MB) - *테스트 12 〉 (0.18ms, 76.7MB) - *테스트 13 〉 (0.14ms, 81.4MB) - * - */ - -/** - * 모든 컴퓨테에 대해 반복 - * 방문하지 않았으면 dfs 호출 - * 한 네트워크의 모든 컴퓨터 방문했음로 answer증가 - * dfs - * 현재 컴퓨터(start)를 방문 처리 - * 다른 컴퓨터들 확인 - * 자기 자신(start)이 아닌 경우 && 현재 컴퓨터와 연결된 경우 && 방문하지 않았을 경우 - * 해당 컴퓨터에 대해서 다시 dfs 호출 - */ - -public class Solution { - - boolean[] visited; - - public int solution(int n, int[][] computers) { - int answer = 0; - visited = new boolean[n]; - for (int i = 0; i < n; i++) { - if (!visited[i]) { - dfs(computers,i); - answer++; - } - } - - return answer; - } - - void dfs(int[][] computers, int start) { - visited[start] = true; - - for (int i = 0; i < computers.length; i++) { - if (start != i && computers[start][i] == 1 && !visited[i]) { - dfs(computers, i); - } - } - } - - public static void main(String[] args) { - System.out.println(new Solution().solution(3, new int[][]{ - {1, 1, 0}, - {1, 1, 0}, - {0, 0, 1} - })); - System.out.println(new Solution().solution(3, new int[][]{ - {1, 1, 0}, - {1, 1, 1}, - {0, 1, 1} - })); - } -} diff --git a/src/week04/gahyun/p1/Solution.java b/src/week04/gahyun/p1/Solution.java deleted file mode 100644 index aecdca5..0000000 --- a/src/week04/gahyun/p1/Solution.java +++ /dev/null @@ -1,59 +0,0 @@ -package week04.gahyun.p1; - -import java.util.*; -/** - https://school.programmers.co.kr/learn/courses/30/lessons/43163 - 시간, 메모리: - 테스트 1 〉 통과 (0.29ms, 77.8MB) - 테스트 2 〉 통과 (0.54ms, 80.2MB) - 테스트 3 〉 통과 (0.37ms, 81.5MB) - 테스트 4 〉 통과 (0.30ms, 67.6MB) - 테스트 5 〉 통과 (0.06ms, 72MB) - */ - -/** - * BFS 탐색 - * 단어, 변환 수 저장하는 클래스 만들어서 큐에 삽입 - * 문자열 요소 비교해서 하나만 다른지 확인 - * 하나만 다르고, 기존 방문 내역 없으면 큐에 삽입 - * 변환한 단어가 타켓과 같으면 큐에 삽입 전 바로 반환 - * 기존 변환 수에서 1증가 시키기 - */ -class Solution { - - static int[][] dis; - static int[][] move = {{1,0},{-1,0},{0,1},{0,-1}}; - static int n,m; - - public int solution(int[][] maps) { - n = maps.length; - m = maps[0].length; - dis = new int[n][m]; - - - BFS(maps); - if (dis[n-1][m-1]==0) return -1; - else return dis[n-1][m-1]; - } - - public static void BFS(int[][] maps){ - Queue q = new LinkedList<>(); - dis[0][0] = 1; - q.offer(new int[]{0,0}); - - while (!q.isEmpty()){ - int[] cur = q.poll(); - for (int[] d : move){ - int nx = cur[0]+d[0]; - int ny = cur[1]+d[1]; - - if ((nx>=0 && nx=0 && ny0) return; - q.offer(new int[]{nx,ny}); - } - } - } - } -} diff --git a/src/week04/gahyun/p2/Solution.java b/src/week04/gahyun/p2/Solution.java deleted file mode 100644 index 5d4e0d1..0000000 --- a/src/week04/gahyun/p2/Solution.java +++ /dev/null @@ -1,72 +0,0 @@ -package week04.gahyun.p2; - -import java.util.*; - -/** - https://school.programmers.co.kr/learn/courses/30/lessons/43163 - 시간, 메모리: - 테스트 1 〉 통과 (0.29ms, 77.8MB) - 테스트 2 〉 통과 (0.54ms, 80.2MB) - 테스트 3 〉 통과 (0.37ms, 81.5MB) - 테스트 4 〉 통과 (0.30ms, 67.6MB) - 테스트 5 〉 통과 (0.06ms, 72MB) - */ - -/** - * BFS 탐색 - * 단어, 변환 수 저장하는 클래스 만들어서 큐에 삽입 - * 문자열 요소 비교해서 하나만 다른지 확인 - * 하나만 다르고, 기존 방문 내역 없으면 큐에 삽입 - * 변환한 단어가 타켓과 같으면 큐에 삽입 전 바로 반환 - * 기존 변환 수에서 1증가 시키기 - */ -class Solution { - public int solution(String begin, String target, String[] words) { - if (!Arrays.asList(words).contains(target)) return 0; //배열에 target있는지 검증 - return BFS(begin, target, words); - } - - public int BFS(String begin, String target, String[] words){ - Queue q = new LinkedList<>(); - q.offer(new WordDis(begin, 0)); - boolean[] visited = new boolean[words.length]; // 방문 여부 - - while (!q.isEmpty()){ - WordDis cur = q.poll(); - - for (int i=0;i1) return false; - } - } - if (cnt==1) return true; - return false; - } -} - -class WordDis{ - String word; // 단어 - int dis; // 변환 수 - public WordDis(String word, int dis){ - this.word = word; - this.dis = dis; - } -} diff --git a/src/week04/gahyun/p3/Solution.java b/src/week04/gahyun/p3/Solution.java deleted file mode 100644 index a849943..0000000 --- a/src/week04/gahyun/p3/Solution.java +++ /dev/null @@ -1,53 +0,0 @@ -package week04.gahyun.p3; -/** - https://school.programmers.co.kr/learn/courses/30/lessons/60057 - 시간, 메모리: - 테스트 1 〉 통과 (0.10ms, 75.4MB) - 테스트 2 〉 통과 (0.39ms, 75MB) - 테스트 3 〉 통과 (0.21ms, 74.5MB) - 테스트 4 〉 통과 (0.11ms, 76.9MB) - 테스트 5 〉 통과 (0.03ms, 76.2MB) - */ - -/** - * l에 따라 압축되는 길이 구해서 최소 길이 구하기 - * target==cur? - * O -> cnt++; - * X -> 이전 cnt, target 더해주기; cnt, target 갱신 - * 마지막 문자열 더해주기 - */ -class Solution { - public static void main(String[] args) { - String s = "ababcdcdababcdcd"; - int answer = s.length(); // 문자열 줄이지 못하는 경우 - - for (int l = 1; l <= s.length() / 2; l++) { // 자르는 단위 - StringBuilder sb = new StringBuilder(); - int cnt = 1; // 연속으로 몇 번 일치하는지 - String target = s.substring(0, l); - - for (int i = l; i < s.length(); i += l) { - String cur = s.substring(i, Math.min(i + l, s.length())); - if (target.equals(cur)) { - cnt++; - } else { - if (cnt == 1) { // 이전에 연속되지 않았을 경우 - sb.append(target); - } else { // 연속된 경우 - sb.append(cnt).append(target); - } - target = cur; - cnt = 1; - } - } - if (cnt == 1) { // 이전에 연속되지 않았을 경우 - sb.append(target); - } else { // 연속된 경우 - sb.append(cnt).append(target); - } - answer = Math.min(sb.length(), answer); - } - - System.out.println(answer); - } -} diff --git a/src/week04/jaewon/p1/Main.java b/src/week04/jaewon/p1/Main.java deleted file mode 100644 index f5decc4..0000000 --- a/src/week04/jaewon/p1/Main.java +++ /dev/null @@ -1,58 +0,0 @@ -import java.util.*; - -/* - 문제 링크 : https://www.acmicpc.net/problem/1844 - 시간, 메모리: - 테스트 1 〉 통과 (0.22ms, 87.2MB) - 테스트 2 〉 통과 (0.19ms, 79.4MB) - 테스트 3 〉 통과 (0.21ms, 80MB) - 테스트 4 〉 통과 (0.15ms, 71.5MB) - 테스트 5 〉 통과 (0.15ms, 72.3MB) - */ - -/** - * BFS 탐색 - * (0, 0) -> (n - 1, m - 1) 최단 경로 거리 계산 - */ - -class Solution { - - int[][] dirs = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; - - public int solution(int[][] maps) { - Queue q = new LinkedList<>(); - - boolean[][] visited = new boolean[100][100]; - - int N = maps.length - 1; - int M = maps[0].length - 1; - - q.add(new int[] { 0, 0 }); - - while (!q.isEmpty()) { - int[] cur = q.poll(); - - for (int[] d : dirs) { - int nl = cur[0] + d[0]; - int nc = cur[1] + d[1]; - - if (nl == N && nc == M) { - return maps[cur[0]][cur[1]] + 1; - } - - if (nl < 0 || nl > N || nc < 0 || nc > M) - continue; - if (maps[nl][nc] == 0) - continue; - - if (!visited[nl][nc]) { - visited[nl][nc] = true; - q.add(new int[] { nl, nc }); - maps[nl][nc] = maps[cur[0]][cur[1]] + 1; - } - } - } - - return -1; - } -} \ No newline at end of file diff --git a/src/week04/jaewon/p2/Main.java b/src/week04/jaewon/p2/Main.java deleted file mode 100644 index 1b0c0df..0000000 --- a/src/week04/jaewon/p2/Main.java +++ /dev/null @@ -1,61 +0,0 @@ -import java.util.*; - -/* - 문제 링크 : https://www.acmicpc.net/problem/43163 - 시간, 메모리: - 테스트 1 〉 통과 (0.14ms, 81.8MB) - 테스트 2 〉 통과 (0.23ms, 82.5MB) - 테스트 3 〉 통과 (0.53ms, 82.6MB) - 테스트 4 〉 통과 (0.11ms, 72.4MB) - 테스트 5 〉 통과 (0.10ms, 77.2MB) - */ - -/** - * BFS 탐색 - * words 인덱스, 변환한 횟수를 queue에 넣기 - * 큐에서 꺼내며 target과 동일한지 비교 - * target과 다르면 words에 있는 문자열과 비교하며 문자 개수가 1개만 차이난다면 해당 word 방문 - */ -class Solution { - - int countDiff(String str1, String str2) { - int cnt = 0; - for (int i = 0; i < str1.length(); ++i) { - if (str1.charAt(i) != str2.charAt(i)) { - cnt++; - } - } - return cnt; - } - - public int solution(String begin, String target, String[] words) { - boolean[] visited = new boolean[words.length]; - - Queue q = new LinkedList<>(); - - for (int i = 0; i < words.length; ++i) { - if (countDiff(begin, words[i]) == 1) { - q.add(new int[] { i, 1 }); - visited[i] = true; - } - } - - while (!q.isEmpty()) { - int[] cur = q.poll(); - - if (target.equals(words[cur[0]])) { - return cur[1]; - } - - for (int i = 0; i < words.length; ++i) { - if (visited[i]) continue; - if (countDiff(words[cur[0]], words[i]) == 1) { - q.add(new int[] { i, cur[1] + 1 }); - visited[i] = true; - } - } - } - - return 0; - } -} \ No newline at end of file diff --git a/src/week04/jaewon/p3/Main.java b/src/week04/jaewon/p3/Main.java deleted file mode 100644 index ed4cb13..0000000 --- a/src/week04/jaewon/p3/Main.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - 문제 링크 : https://www.acmicpc.net/problem/60057 - 시간, 메모리: - 테스트 1 〉 통과 (0.08ms, 75.8MB) - 테스트 2 〉 통과 (0.54ms, 79MB) - 테스트 3 〉 통과 (0.31ms, 84.2MB) - 테스트 4 〉 통과 (0.09ms, 73.5MB) - 테스트 5 〉 통과 (0.02ms, 75.4MB) - */ - -/** - * 문자 단위 개수 당 이전에 등장한 문자열과 동일한지 비교 - * 비교후, 같다면 streak 1 증가 - * 다르면 길이 cnt 변수에 현재 문자 단위 길이와 streak 길이 만큼 추가하고, streak 1로 초기화 - * 마지막에는 streak 숫자에 해당하는 문자열 길이 추가 - */ - -class Solution { - - int compress(String str, int tokenLen) { - int streak = 1; - int cnt = 0; - String prev = ""; - - for (int i = 0; i < str.length(); i += tokenLen) { - String token = str.substring(i, Math.min(i + tokenLen, str.length())); - if (prev.equals(token)) { - streak++; - } else { - if (streak != 1) { - cnt += String.valueOf(streak).length(); - streak = 1; - } - cnt += token.length(); - prev = token; - } - } - if (streak != 1) { - cnt += String.valueOf(streak).length(); - } - return cnt; - } - - public int solution(String s) { - int answer = compress(s, 1); - for (int i = 2; i < s.length(); ++i) { - answer = Math.min(answer, compress(s, i)); - } - return answer; - } -} diff --git a/src/week04/sunghee/p1/Solution.java b/src/week04/sunghee/p1/Solution.java deleted file mode 100644 index e11dc85..0000000 --- a/src/week04/sunghee/p1/Solution.java +++ /dev/null @@ -1,64 +0,0 @@ -package week04.sunghee.p1; - - -/** - * 문제 링크 :https://school.programmers.co.kr/learn/courses/30/lessons/1844 - * 테스트 1 〉 통과 (0.13ms, 76.8MB) - */ - -/** - * bfs로 풀이 - * queue의 값을 꺼내 동,서,남,북 방향을 돌면서 만족하는 값(ny, nx가 범위 안에 속하고 maps[ny][nx]의 값이 1인 경우) - * maps[ny][nx] 에 현재 maps의 값 + 1을 더해줌(depth계산) - * queue에 값을 넣음 - * 위의 과정을 queue가 빌때까지 또는 ny, nx가 적군의 위치이면 종료 - * - * maps의 적군의 위치 값 -1을 반환 - */ - -import java.util.LinkedList; -import java.util.Queue; - -class Solution { - - int[] dx = {1, 0, -1, 0}; - int[] dy = {0, 1, 0, -1}; - - public int solution(int[][] maps) { - bfs(maps); - int answer = maps[maps.length-1][maps[0].length-1] -1; - return answer == 0 ? -1 : answer; - } - - void bfs(int[][] maps) { - int x = 0; - int y = 0; - - maps[y][x] = 2; - Queue queue = new LinkedList<>(); - queue.offer(new int[]{y, x}); - - while(!queue.isEmpty()){ - int[] cur = queue.poll(); - int curY = cur[0]; - int curX = cur[1]; - - for (int i = 0; i < 4; i++) { - int ny = curY + dy[i]; - int nx = curX + dx[i]; - - if(ny < 0 || nx < 0 || ny > maps.length-1 || nx > maps[0].length-1 || maps[ny][nx] != 1) continue; - - maps[ny][nx] = maps[curY][curX] + 1; - - if(ny == maps.length-1 && nx == maps[0].length-1) return; - queue.offer(new int[]{ny, nx}); - } - } - } - - public static void main(String[] args) { - System.out.println(new Solution().solution(new int[][]{{1,0,1,1,1}, {1,0,1,0,1}, {1,0,1,1,1}, {1,1,1,0,1},{0,0,0,0,1}})); - System.out.println(new Solution().solution(new int[][]{{1,0,1,1,1}, {1,0,1,0,1}, {1,0,1,1,1}, {1,1,1,0,0},{0,0,0,0,1}})); - } -} diff --git a/src/week04/sunghee/p2/Solution.java b/src/week04/sunghee/p2/Solution.java deleted file mode 100644 index cbce6ba..0000000 --- a/src/week04/sunghee/p2/Solution.java +++ /dev/null @@ -1,76 +0,0 @@ -package week04.sunghee.p2; - - -/** - * 문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/43163 - * 테스트 1 〉 통과 (0.42ms, 75.5MB) - */ - -/** - * bfs로 풀이 - */ - -import java.util.LinkedList; -import java.util.Queue; - -class Solution { - - private static class State { - public final String word; - public final int step; - - private State(String word, int step) { - this.word = word; - this.step = step; - } - } - - private static boolean isConvertable(String s1, String s2) { - int diffCnt = 0; - for (int i = 0; i < s1.length(); i++) { - if(s1.charAt(i) != s2.charAt(i)) diffCnt++; - } - - return diffCnt == 1; - } - - - public int solution(String begin, String target, String[] words) { - boolean[] isVisited = new boolean[words.length]; - - Queue queue = new LinkedList<>(); - queue.add(new State(begin, 0)); - - //5. 탐색 진행 - while (!queue.isEmpty()) { - State state = queue.poll(); - - //6. 현재 상태 처리 - if (state.word.equals(target)) { - return state.step; - } - - for (int i = 0; i < words.length; i++) { - String next = words[i]; - if (!isConvertable(state.word, next) || isVisited[i]) continue; - - //9. 방문 처리 && 상태 정의 - isVisited[i] = true; //검사 통과한 상태는 전이될 수 있는 상태로 방문 처리 - queue.add(new State(next, state.step + 1)); //탐색 공간에 추가 - } - - } - - //모든 공간을 탐색 했는데 정답 상태를 방문하지 못하면 0를 반환 - return 0; - - } - - - - - public static void main(String[] args) { - System.out.println(new Solution().solution("hit", "cog", new String[]{"hot", "dot", "dog", "lot", "log", "cog"})); - System.out.println(new Solution().solution("hit", "cog", new String[]{"hot", "dot", "dog", "lot", "log"})); - } -} diff --git a/src/week04/sunghee/p3/Solution.java b/src/week04/sunghee/p3/Solution.java deleted file mode 100644 index 4df8c31..0000000 --- a/src/week04/sunghee/p3/Solution.java +++ /dev/null @@ -1,60 +0,0 @@ -package week04.sunghee.p3; - -/* - * 문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/60057 - * 테스트 1 〉 통과 (0.07ms, 77MB) - */ - -public class Solution { - public int solution(String s) { - int answer = s.length(); - - //단어 단위가 단어길의의 절반을 넘어가면 2번이상 반복하지 않기 때문에 소용 없음 - for (int i = 1; i <= s.length()/2; i++) { - //비교 시 현재 단어 - String nowStr = s.substring(0, i); - //단어 count, s.substring(0, i)에 대해서 미리 cnt +1 - int cnt = 1; - - //압축한 단어 - StringBuilder resultStr = new StringBuilder(); - - //단어 비교하며 단어 압축 - for (int j = i; j 1) { - //cnt가 1보다 크면 cnt 앞축한 단어에 append - resultStr.append(cnt); - } - //단어 append - resultStr.append(nowStr); - - nowStr = nextStr; - cnt = 1; - } - - } - //마지막 단어 append - if (cnt > 1) { - resultStr.append(cnt); - } - resultStr.append(nowStr); - - - answer = Math.min(answer, resultStr.length()); - - - } - - return answer; - } -} diff --git a/src/week05/gahyun/p1/Main.java b/src/week05/gahyun/p1/Main.java deleted file mode 100644 index 1dd746f..0000000 --- a/src/week05/gahyun/p1/Main.java +++ /dev/null @@ -1,95 +0,0 @@ -package week05.gahyun.p1; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.PriorityQueue; -import java.util.StringTokenizer; - -/** - * https://www.acmicpc.net/problem/1202 - * 메모리: 127064KB - * 시간: 1512ms - */ - -/** - * 보석 무게, 가격 담은 클래스 생성 - * 보석 객체 리스트 -> 무게 오름차순, 가격 내림차순 정렬 - * 가방 무게 리스트 -> 오름차순 정렬 - * 가방 리스트에 대해 반복 - * - 보석 객체 리스트 순회하며 가방 무게 초과하지 않는지 확인 - * - 초과하지 않으면 우선순위 큐에 저장( 가격 내림차순 정렬) - * - 첫번째 요소 빼서 무게 더해줌 - * - 다음 반복부터는 기존에 봤던 인덱스 다음부터 보면됨 - */ - -public class Main { - public static void main(String[] args) throws IOException { - long answer = 0; // int 아님 - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - StringTokenizer st = new StringTokenizer(br.readLine()); - int N = Integer.parseInt(st.nextToken()); - int K = Integer.parseInt(st.nextToken()); - - int[] bags = new int[K]; - List jewels = new ArrayList<>(); - - // 보석 무게, 가격 입력 받아 객체 리스트 생성하기 - for (int i = 0; i < N; i++) { - st = new StringTokenizer(br.readLine()); - int M = Integer.parseInt(st.nextToken()); - int V = Integer.parseInt(st.nextToken()); - jewels.add(new Jewel(M, V)); - } - - // 무게 오름차순, 가격 내림차순 정렬 - jewels.sort((j1, j2) -> { - int c = Integer.compare(j1.weight, j2.weight); - if (c != 0) - return c; - c = Integer.compare(j2.price, j1.price); - return c; - }); - - // 가방 초기화 - for (int i = 0; i < K; i++) { - bags[i] = Integer.parseInt(br.readLine()); - } - Arrays.sort(bags); // 오름차순 정렬 - // System.out.println(jewels); - - - PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder()); // 가격 내림차순 정렬 - for (int i = 0, j = 0; i < K; i++) {// i-> 가방 인덱스, j -> 보석 객체 인덱스 - while (j < N && bags[i] >= jewels.get(j).weight) { // 가방이 용량 초과하지 않을 때까지 더하기 - pq.add(jewels.get(j).price); - j++; // 가방 무게 무거워지므로 이전 보석들은 다 들어감 -> 다음 보석부터 검사하면 됨 - } - // 제일 높은 가격 더하기 - if (!pq.isEmpty()) { - answer += pq.poll(); - } - } - - System.out.println(answer); - } -} - -class Jewel { - int weight; - int price; - - public Jewel(int weight, int price) { - this.weight = weight; - this.price = price; - } - - @Override - public String toString() { - return String.format("{weight = %d, price = %d} ", weight, price); - } -} \ No newline at end of file diff --git a/src/week05/gahyun/p2/Solution.java b/src/week05/gahyun/p2/Solution.java deleted file mode 100644 index 3b2cd9f..0000000 --- a/src/week05/gahyun/p2/Solution.java +++ /dev/null @@ -1,88 +0,0 @@ -package week05.gahyun.p2; - -import java.util.*; - -/** - * https://school.programmers.co.kr/learn/courses/30/lessons/42579# - * 테스트 1 〉 통과 (2.95ms, 76.2MB) - * 테스트 2 〉 통과 (3.02ms, 75.2MB) - * 테스트 3 〉 통과 (2.54ms, 69.5MB) - * 테스트 4 〉 통과 (3.65ms, 78MB) - * 테스트 5 〉 통과 (4.50ms, 77.5MB) - */ - -/** - * 장르별 플레이수 treeMap으로 저장해 내림차순 정렬 - * Music 객체 리스트에 인덱스, 장르수, 플레이수 저장 - * 해당 리스트에서 map 장르순, 재생횟수 내림 차순 정렬 - * 정렬된 리스트 순회하며 인덱스를 장르별 최대 2개씩 담기 - */ -class Solution { - public int[] solution(String[] genres, int[] plays) { - List answer = new ArrayList<>(); - Map genreMap = new TreeMap<>(Collections.reverseOrder()); //장르별 플레이수 내림차순 정렬 - List musicList = new ArrayList<>(); // 노래 정보 저장 - - for (int i=0;i { - // 장르별 - int c = Integer.compare(genreMap.get(m2.genre), genreMap.get(m1.genre)); //인덱스 비교 map에서 m1이 더 앞에 있어야 함 - if (c != 0) - return c; - - // 재생횟수 내림차순 - c = Integer.compare(m2.cnt, m1.cnt); - return c; - }); - - String preGenre=""; // 이전 장르 - int genreCnt = 0; // 연속된 장르 등장수 - - for (Music music : musicList) { - if (music.genre.equals(preGenre)) { - genreCnt++; - if (genreCnt >= 3) - continue; // 최대 2곡 - } else { // 장르 갱신 - genreCnt = 1; - preGenre = music.genre; - } - answer.add(music.ind); // 정답 배열에 인덱스 삽입 - } - - // list -> int[] - return answer.stream() - .mapToInt(i -> i) - .toArray(); - } - -} - -class Main { - public static void main(String[] args) { - int[] answer = new Solution().solution(new String[] {"classic", "classic", "classic", "classic", "pop"}, - new int[] {50, 60, 100, 30, 8000}); - System.out.println(Arrays.toString(answer)); - } -} - -class Music{ - int ind; - String genre; - int cnt; - - public Music(int ind, String genre, int cnt){ - this.ind = ind; - this.genre = genre; - this.cnt = cnt; - } - //디버깅 - @Override - public String toString() { - return String.format("Music{ind=%d, genre='%s', cnt=%d}", ind, genre, cnt); - } -} \ No newline at end of file diff --git a/src/week05/gahyun/p3/Solution.java b/src/week05/gahyun/p3/Solution.java deleted file mode 100644 index 1d2e6d6..0000000 --- a/src/week05/gahyun/p3/Solution.java +++ /dev/null @@ -1,80 +0,0 @@ -package week05.gahyun.p3; - -import java.util.LinkedList; -import java.util.Queue; - -/** - * https://school.programmers.co.kr/learn/courses/30/lessons/87694 - * 테스트 1 〉 통과 (0.36ms, 75.3MB) - * 테스트 2 〉 통과 (0.35ms, 67.8MB) - * 테스트 3 〉 통과 (0.53ms, 78.8MB) - * 테스트 4 〉 통과 (0.37ms, 65.8MB) - * 테스트 5 〉 통과 (0.49ms, 78.6MB) - */ - -/** - * 최단 거리 -> BFS - * ㄷ자 이동하기 위해 2배 확대 시키기 - * 겹치는 부분 모두 칠하고 내부 부분 제외해서 외곽선 구하기 - * 도착지점 거리 구하고 다시 2로 나누기 - */ -public class Solution { - - static int[] dx = {0, 0, -1, 1}; - static int[] dy = {-1, 1, 0, 0}; - static boolean[][] available; - static int[][] graph; - - public int solution(int[][] rectangle, int characterX, int characterY, int itemX, int itemY) { - available = new boolean[102][102]; // 이동 가능 여부 - graph = new int[102][102]; - - for (int[] data : rectangle) {// 겹치는 부분 채우기 - for (int y = data[1] * 2; y <= data[3] * 2; y++) { // 2배로 늘려서 ㄷ으로 갈 수 있게 함 - for (int x = data[0] * 2; x <= data[2] * 2; x++) { - available[x][y] = true; - } - } - } - for (int[] data : rectangle) { // 내부 없애고 외곽만 남기기 - for (int y = data[1] * 2 + 1; y < data[3] * 2; y++) { - for (int x = data[0] * 2 + 1; x < data[2] * 2; x++) { - available[x][y] = false; - } - } - } - - BFS(characterX * 2, characterY * 2, itemX * 2, itemY * 2); - - return graph[itemX * 2][itemY * 2] / 2; // 2배 늘린거 반영 - } - - public void BFS(int cx, int cy, int ix, int iy) { - Queue queue = new LinkedList<>(); - queue.add(new Pos(cx, cy)); - graph[cx][cy] = 1; - - while (!queue.isEmpty()) { - Pos current = queue.poll(); - - for (int i = 0; i < 4; i++) { - int nx = current.x + dx[i]; - int ny = current.y + dy[i]; - - // 주어진 범위 넘지 않음 && 외곽선 && 기존에 방문하지 않음 - if (nx >= 0 && ny >= 0 && nx < 102 && ny < 102 && available[nx][ny] && graph[nx][ny] == 0) { - graph[nx][ny] = graph[current.x][current.y] + 1; - queue.add(new Pos(nx, ny)); - } - } - } - } -} - -class Pos { - int x, y; - public Pos(int x, int y) { - this.x = x; - this.y = y; - } -} \ No newline at end of file diff --git a/src/week05/sunghee/p1/Main.java b/src/week05/sunghee/p1/Main.java deleted file mode 100644 index 3c410b1..0000000 --- a/src/week05/sunghee/p1/Main.java +++ /dev/null @@ -1,98 +0,0 @@ -package week05.sunghee.p1; - - -/** - * 문제 링크 :https://www.acmicpc.net/problem/1202 - * 메모리 : 125456 KB - * 시간 : 1616ms - */ - -/** - * 다른 사람 풀이 보고 품 - * 보석은 무게(오름차순), 가격(내림차순) 으로 정렬 - * 가방은 무게(오름차순) 정렬 - * 가방 기준으로 for문 - * 현재 가방의 무게보다 무게가 작거나 같은 보석을 우선순위큐(가격기준)에 추가 - * 큐.poll() 해서 정답에 더해줌 - * - * 3퍼 에러 -> 최대 리턴 값 1,000,000 * 300,000 = 300,000,000,000 -> int 범위 벗어남 - */ - - -import java.util.*; -import java.io.*; - -class Main { - - static class Jewelry implements Comparable { - int mass, value; - - public Jewelry(int mass, int value) { - this.mass = mass; - this.value = value; - } - - // 오름차순으로 정렬 - // 1(크다), (0) 같다, -1 작다 - @Override - public int compareTo(Jewelry o) { - if(this.mass == o.mass) { - //무게가 같을경우 가격을 내림차순으로 정렬. - // this 작은거, o가 큰거 - // 큰 - 작은 -> 큰순으로 - return o.value - this.value; - } - //작은거 - 큰거 -> 음수 -> 작은 순으로 - return this.mass - o.mass; - } - - } - - static int N, K; - static int[] bags; - static Jewelry[] jewelries; - - public static void main(String[] args) throws Exception{ - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - StringTokenizer st = new StringTokenizer(br.readLine()); - - N = Integer.parseInt(st.nextToken()); - K = Integer.parseInt(st.nextToken()); - - jewelries = new Jewelry[N]; - bags = new int[K]; - - for(int i = 0; i < N; i++) { - st = new StringTokenizer(br.readLine()); - int m = Integer.parseInt(st.nextToken()); - int v = Integer.parseInt(st.nextToken()); - jewelries[i] = new Jewelry(m, v); - } - - for(int i = 0; i pq = new PriorityQueue<>(Collections.reverseOrder()); - long answer = 0; - - for(int i = 0, j = 0; i < K; i++) { - //현재 가방의 무게보다 작거나, 같은 보석을 모두 큐에 - while (j < N && jewelries[j].mass <= bags[i]) { - pq.offer(jewelries[j++].value); - } - - if(!pq.isEmpty()) { - //value가 가장 큰 값으로 - answer += pq.poll(); - } - } - System.out.println(answer); - } -} diff --git a/src/week05/sunghee/p2/Solution.java b/src/week05/sunghee/p2/Solution.java deleted file mode 100644 index c5b0333..0000000 --- a/src/week05/sunghee/p2/Solution.java +++ /dev/null @@ -1,68 +0,0 @@ -package week05.sunghee.p2; - -/** - * 문제 링크 :https://school.programmers.co.kr/learn/courses/30/lessons/42579 - * 테스트 1 〉 통과 (2.92ms, 76MB) - * 테스트 2 〉 통과 (2.99ms, 73.9MB) - * 테스트 3 〉 통과 (2.98ms, 81.4MB) - * 테스트 4 〉 통과 (3.26ms, 75.4MB) - * 테스트 5 〉 통과 (3.47ms, 74.5MB) - * 테스트 6 〉 통과 (4.26ms, 74.9MB) - * 테스트 7 〉 통과 (4.10ms, 80.2MB) - * 테스트 8 〉 통과 (4.19ms, 75.2MB) - * 테스트 9 〉 통과 (2.91ms, 76.4MB) - * 테스트 10 〉 통과 (3.26ms, 74.3MB) - * 테스트 11 〉 통과 (4.12ms, 67.1MB) - * 테스트 12 〉 통과 (3.23ms, 75.6MB) - * 테스트 13 〉 통과 (4.04ms, 73.9MB) - * 테스트 14 〉 통과 (3.54ms, 73.1MB) - * 테스트 15 〉 통과 (5.01ms, 82.3MB) - */ - -/** - * 1. 장르별 재생횟수 많은 순으로 정렬 - * 2. 정렬한 장르 순으로 반복 - * 재생 횟수가 많은 기준응로 정렬 - * 제일 많은 곡 2곡(없으면 1곡만) 정답에 추가 - */ -import java.util.*; - -class Solution { - - public int[] solution(String[] genres, int[] plays) { - - HashMap genresTotalCnt = new HashMap<>(); - HashMap> songsPlays = new HashMap<>(); - - for (int i =0; i < genres.length; i++) { - String genre = genres[i]; - int playCnt = plays[i]; - int totalCnt = 0; - HashMap songsMap = new HashMap<>(); - - if (genresTotalCnt.containsKey(genre)) { - totalCnt = genresTotalCnt.get(genre); - songsMap = songsPlays.get(genre); - } - - genresTotalCnt.put(genre, totalCnt + playCnt); - songsMap.put(i, playCnt); - songsPlays.put(genre, songsMap); - } - - List genreSet = new ArrayList<>(genresTotalCnt.keySet()); - genreSet.sort((g1, g2) -> (genresTotalCnt.get(g2) - genresTotalCnt.get(g1))); - - ArrayList answer = new ArrayList<>(); - - for(String genre : genreSet) { - HashMap play = songsPlays.get(genre); - List songSet = new ArrayList<>(play.keySet()); - songSet.sort((s1, s2) -> (play.get(s2) - play.get(s1))); - - answer.add(songSet.get(0)); - if(songSet.size() > 1) answer.add(songSet.get(1)); - } - return answer.stream().mapToInt(i -> i).toArray(); - } -} diff --git a/src/week05/sunghee/p3/Solution.java b/src/week05/sunghee/p3/Solution.java deleted file mode 100644 index f3f0ab8..0000000 --- a/src/week05/sunghee/p3/Solution.java +++ /dev/null @@ -1,85 +0,0 @@ -package week05.sunghee.p3; - -/** - * 문제 링크 : https://school.programmers.co.kr/learn/courses/30/lessons/87694 - * 테스트 1 〉 통과 (0.18ms, 78.1MB) - * 테스트 2 〉 통과 (0.19ms, 75.8MB) - * 테스트 3 〉 통과 (0.21ms, 76.5MB) - * 테스트 4 〉 통과 (0.17ms, 78.1MB) - * 테스트 5 〉 통과 (0.16ms, 77.2MB) - * 테스트 6 〉 통과 (0.12ms, 77.5MB) - * 테스트 7 〉 통과 (0.24ms, 86.3MB) - * 테스트 8 〉 통과 (0.27ms, 71.7MB) - * 테스트 9 〉 통과 (1.68ms, 72.6MB) - * 테스트 10 〉 통과 (1.29ms, 71MB) - * 테스트 11 〉 통과 (2.00ms, 73.2MB) - * 테스트 12 〉 통과 (1.89ms, 78.1MB) - * 테스트 13 〉 통과 (0.90ms, 77MB) - * 테스트 14 〉 통과 (0.40ms, 81.2MB) - * 테스트 15 〉 통과 (0.22ms, 73.9MB) - */ - -/** - * 풀이보고 품(배율 조절 관련해서 -> 안하면 겹치는 모서리 생김) - * bfs 사용 - * map에서 테두리는 2, 도형이 포함된 부부는 1로 지정 - */ - -import java.util.*; - -public class Solution { - int[][] map = new int[101][101]; - - public int solution(int[][] rectangle, int characterX, int characterY, int itemX, int itemY) { - - for(int[] rect : rectangle) { - int x1 = rect[0] * 2; - int y1 = rect[1] * 2; - int x2 = rect[2] * 2; - int y2 = rect[3] * 2; - - for(int x = x1; x < x2 +1; x++) { - for(int y = y1; y < y2 + 1; y ++) { - if(map[y][x] == 1) continue; - map[y][x] = 1; - if(y == y1 || y == y2 || x == x1 || x == x2) { - map[y][x] = 2; - } - } - } - } - - bfs(characterX * 2, characterY * 2, itemX * 2, itemY * 2); - return (map[itemY * 2][itemX * 2] - 3) /2; - } - - void bfs(int characterX, int characterY, int itemX, int itemY) { - int[] dy = {0, 0, 1, -1}; - int[] dx = {1, -1, 0, 0}; - - Queue queue = new LinkedList<>(); - map[characterY][characterX] = 3; - queue.offer(new int[]{characterY, characterX}); - - while(!queue.isEmpty()) { - - int[] cur = queue.poll(); - int curY = cur[0]; - int curX = cur[1]; - - for(int i = 0; i < 4; i++) { - int ny = curY + dy[i]; - int nx = curX + dx[i]; - - if(ny < 0 || ny > 100 || nx< 0 || nx > 100 || map[ny][nx] != 2) continue; - - map[ny][nx] = map[curY][curX] + 1; - - if(ny == itemY && nx == itemX) return; - - queue.offer(new int[]{ny, nx}); - } - } - - } -}