Dazzling 개발 노트

[이것이 취업을 위한 코딩테스트다] Ch04. 구현 - 왕실의 나이트 (Java) 본문

Algorithm

[이것이 취업을 위한 코딩테스트다] Ch04. 구현 - 왕실의 나이트 (Java)

dj._.dazzling 2023. 7. 13. 17:02

문제

 

풀이/후기

8가지 방향을 정의하여

해당 방향이 지도 안에서 갈 수 있는 곳이라면 결과값++

코드

package ThisIsCT;

import java.io.*;

public class ch04_03 {
	// Ch.04 구현
	// 왕실의 나이트

	static int x, y;
	static int[] dirX = {1, 1, -1, -1, 2, 2, -2, -2};
	static int[] dirY = {2, -2, 2, -2, 1, -1, 1, -1};
	static int result = 0;

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] str = br.readLine().split("");
		String tempStr = str[0];
		y = Integer.parseInt(str[1]);
		if (tempStr.equals("a")) x = 1;
		else if (tempStr.equals("b")) x = 2;
		else if (tempStr.equals("c")) x = 3;
		else if (tempStr.equals("d")) x = 4;
		else if (tempStr.equals("e")) x = 5;
		else if (tempStr.equals("f")) x = 6;
		else if (tempStr.equals("g")) x = 7;
		else if (tempStr.equals("h")) x = 8;

		movingFn();
		System.out.println(result);
	}

	/*
	 * 상 (2,1) (2,-1)
		하 (-2,1) (-2,-1)
		좌 (1,-2) (-1,-2)
		우 (1,2) (-1,2)
	 * */

	static void movingFn() {

		for (int i=0; i<8; i++) {
			int tempX = x + dirX[i];
			int tempY = y + dirY[i];

			if (tempX > 0 && tempX <= 8 && tempY > 0 && tempY <= 8) {
				result++;
			}
		}


	}
    
    
    //함수 아래처럼도 사용 가능
    	static void movingFn2() {

		for (int[] step : steps) {
			int tempX = x + step[0];
			int tempY = y + step[1];

			if (tempX > 0 && tempX <= 8 && tempY > 0 && tempY <= 8) {
				result++;
			}
		}

	}
}

Commit

https://github.com/allrightDJ0108/CodingTestStudy/commit/c4cfe9d82dba294a70ce6b6aa59f0e0a11141dac

 

이것이 취업을 위한 코딩테스트다 Ch04. 구현 - 왕실의 나이트 · allrightDJ0108/CodingTestStudy@c4cfe9d

allrightDJ0108 committed Jul 13, 2023

github.com

https://github.com/allrightDJ0108/CodingTestStudy/commit/8b32b0ac4966f4244a79032d8997e2da97578018

 

이것이 취업을 위한 코딩테스트다 Ch04. 구현 - 왕실의 나이트(다시 풀어보기) · allrightDJ0108/CodingTe

allrightDJ0108 committed Jul 13, 2023

github.com

참고