Dazzling 개발 노트

[이것이 취업을 위한 코딩테스트다] Ch04. 구현 - 상하좌우 (Java) 본문

Algorithm

[이것이 취업을 위한 코딩테스트다] Ch04. 구현 - 상하좌우 (Java)

dj._.dazzling 2023. 7. 10. 17:07

문제

 

풀이/후기

 

코드

package ThisIsCT;

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

public class ch04_01 {
	// Ch.04 구현
	// 예제 4-1. 상하좌우

	static int N;
	static String[] plan;
	static int[][] map;
	static Queue<int[]> q = new LinkedList<int[]>();

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		N = Integer.parseInt(br.readLine());
		map = new int[N][N];

		plan = br.readLine().split(" ");

		bfsFn();
		
		int result[] = q.poll();
		int resX = result[0] + 1;
		int resY = result[1] + 1;
		System.out.println(resX + " "+ resY);

	}

	static void bfsFn() {
		q.add(new int[] { 0, 0 });

		int planIdx = 0;

		while (!q.isEmpty()) {
			int cur[] = q.poll();
			int curX = cur[0];
			int curY = cur[1];
			int nextX = 0, nextY = 0;

			if (plan[planIdx].equals("L")) {
				nextX = curX + 0;
				nextY = curY - 1;

			} else if (plan[planIdx].equals("R")) {
				nextX = curX + 0;
				nextY = curY + 1;
				
			} else if (plan[planIdx].equals("U")) {
				nextX = curX - 1;
				nextY = curY + 0;

			} else if (plan[planIdx].equals("D")) {
				nextX = curX + 1;
				nextY = curY + 0;
			}

			if (nextX >= 0 && nextX < N && nextY >= 0 && nextY < N) {
				q.add(new int[] { nextX, nextY });
			} else {
				q.add(new int[] { curX, curY });
			}

			planIdx++;
			if (planIdx == plan.length) return;
		}

	}
}
import java.io.*;

public class ch04_01_master {
	// Ch.04 구현
	// 예제 4-1. 상하좌우
	// 책에서 풀이한 방법

	static int N;
	static int x = 0, y = 0;
	static int[] dx = {0,0,1,-1};
	static int[] dy = {1,-1,0,0};
	static String[] moveType = {"R","L","D","U" };

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		N = Integer.parseInt(br.readLine());
		String[] plan = br.readLine().split(" ");
		
		for (String i : plan) {
			int nx = 0 ;
			int ny = 0 ;
			for (int j=0; j< moveType.length; j++) {
				if (moveType[j].equals(i)) {
					nx = x + dx[j];
					ny = y + dy[j];
				}
				
			}
			if(nx < 0|| nx >= N || ny < 0 || ny >= N) {
				continue;
			}
			x = nx; y = ny;
		}
		
		System.out.println((x+1) + " "+ (y+1));
		

	}


}

Commit

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

참고