Programming/알고리즘

[java, 알고리즘, 구현] :: 이것이 코딩테스트다 - 왕실의 나이트

구튼탁 2021. 2. 24. 12:20
728x90

2021/02/23 - [Programming/알고리즘] - [java, 알고리즘, 구현] :: 이것이 코딩테스트다 - 시각

2021/02/22 - [Programming/알고리즘] - [java, 알고리즘, 구현] :: 이것이 코딩테스트다 - 상하좌우


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ImplEx03 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input = br.readLine();
        solution(input);
    }
    public static int solution(String input){
        int row = Integer.parseInt(input.charAt(1) + "");
        int col = input.charAt(0) - 97 + 1;

        int [][] steps = {
                {-2, -1}, {-1, -2}, {1, -2}, {2, -1},
                {2, 1}, {1, 2}, {-1, 2}, {-2, 1}
        };

        int result = 0;
        for(int[] step: steps) {
            int nextR = row + step[0];
            int nextC = col + step[1];

            if (nextR >= 1 && nextR <= 8 && nextC >= 1 && nextC <= 8)
                result++;
        }
        System.out.println(result);
        return result;
    }
}

 

1. 현재 위치에서 이동 경로를 더하기

2. 1단계 값이 8x8 좌표 평면에 있는지 확인

 

'상하좌우' 문제에서는 dx, dy 리스트를 선언하여 이동할 방향을 기록했다. 

이 문제에서는 steps 변수가 dx, dy 변수의 기능을 대신하여 수행한다.

 

2가지 형태 모두 자주 사용된다.

 


상하좌우 풀이 코드

package com.algorithm.implementation;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.Buffer;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class ImplEx01 {
    public static void main(String[] args) throws IOException {
        // 이것이 코딩테스트다 - 구현
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());

        StringTokenizer st = new StringTokenizer(br.readLine());
        int[] xy = {1, 1};
        int[] tmp = {1, 1};
        int [] dx = {0, 0, -1, 1};
        int [] dy = {-1, 1, 0, 0};
        char[] directions = {'L', 'R', 'U', 'D'};

        while (st.hasMoreTokens()){
          char direction = st.nextToken().charAt(0);

          for(int i = 0; i < 4; i++){
              if(directions[i] == direction){
                  tmp[0] = xy[0] + dx[i];
                  tmp[1] = xy[1] + dy[i];
              }
          }
          if(tmp[0] < 1 || tmp[1] < 1 || tmp[0] > n || tmp[1] > n)
            continue;
          xy[0] = tmp[0];
          xy[1] = tmp[1];
        }
    }
}
728x90