CodingTest/Java로 푼 코딩 테스트

[Java / 코딩테스트] 사다리타기

마볼링 2023. 10. 5. 20:37

 

1.  생각

  • 일단 n번 반복해야 한다. -> for(n), 임시값 만들기
    • ladder[i][j]에 값이 포함되면, 오른쪽으로 이동, 임시값 +1
    • ladder[i][j]+1에 값이 포함되면, 왼쪽으로 이동, 임시값 -1
  • 임시값 -> 문자(A,B,C,D,E...)로 변경

 

2.  생각대로 코딩

[ 코드 ]

import java.util.*;

public class Problem01 {
    public char[] solution(int n, int[][] ladder){
        char[] answer = new char[n];
        int[] temps = new int[n];
        for (int i = 1; i < n+1; i++) {
            int temp = i;
            for (int j = 0; j < ladder.length; j++) {
                for (int k = 0; k < ladder[j].length; k++) {
                    if (temp == ladder[j][k]) {
                        temp++;
                        break;
                    }
                    if (temp == ladder[j][k] +1) {
                        temp--;
                        break;
                    }
                }
            }
            temps[temp-1] = i;
        }

        String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        for (int i = 0; i < temps.length; i++) {
            answer[i] = LETTERS.substring(temps[i]-1, temps[i]).charAt(0);
        }

        return answer;
    }

    public static void main(String[] args){
        Problem01 T = new Problem01();
        System.out.println(Arrays.toString(T.solution(5, new int[][]{{1, 3}, {2, 4}, {1, 4}})));
        System.out.println(Arrays.toString(T.solution(7, new int[][]{{1, 3, 5}, {1, 3, 6}, {2, 4}})));
        System.out.println(Arrays.toString(T.solution(8, new int[][]{{1, 5}, {2, 4, 7}, {1, 5, 7}, {2, 5, 7}})));
        System.out.println(Arrays.toString(T.solution(12, new int[][]{{1, 5, 8, 10}, {2, 4, 7}, {1, 5, 7, 9, 11}, {2, 5, 7, 10}, {3, 6, 8, 11}})));
    }
}

[결과]

[D, B, A, C, E]
[A, C, B, F, D, G, E]
[C, A, B, F, D, E, H, G]
[C, A, F, B, D, I, E, K, G, L, J, H]

 

3. 강의

[ 코드 ]

import java.util.*;
class Solution {
	public char[] solution(int n, int[][] ladder){
		char[] answer = new char[n];
		for(int i = 0; i < n; i++){
			answer[i] = (char)(i + 65);
		}

		for(int[] line : ladder){
			for(int x : line){
				char tmp = answer[x];
				answer[x] = answer[x-1];
				answer[x-1] = tmp;
			}
		}
		return answer;
	}

	public static void main(String[] args){
		Solution T = new Solution();
		System.out.println(Arrays.toString(T.solution(5, new int[][]{{1, 3}, {2, 4}, {1, 4}})));
		System.out.println(Arrays.toString(T.solution(7, new int[][]{{1, 3, 5}, {1, 3, 6}, {2, 4}})));
		System.out.println(Arrays.toString(T.solution(8, new int[][]{{1, 5}, {2, 4, 7}, {1, 5, 7}, {2, 5, 7}})));
		System.out.println(Arrays.toString(T.solution(12, new int[][]{{1, 5, 8, 10}, {2, 4, 7}, {1, 5, 7, 9, 11}, {2, 5, 7, 10}, {3, 6, 8, 11}})));
	}
}

[ 차이]

  • answer에 문자열로 바로 초기화 하였다
  • 세로줄이 동시에 내려온다고 생각 -> 가로줄마다 answer에 문자열 교체
    ex. {1,3}이면 A(1)<->B(2), C(3)<->D(4)