[코딩테스트] 프로그래머스 49994, 방문길이

2022. 7. 26. 01:32CodingTest

문제

https://school.programmers.co.kr/learn/courses/30/lessons/49994

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

문제접근

  • (y,x) -> (ny,nx) 또는 (ny, nx) -> (y,x) 좌표 이동에 대한 이미 방문을 한적이 있다면 카운팅하지 않고 두 이동 처음 방문이라면 카운팅합니다.
  • 다음 이동인 (ny, nx)에 대해서 범위를 벗어나면 다음 명령어로 넘어갑니다.

 

구현

import java.util.HashMap;
import java.util.Map;

class Solution {

	public boolean move(boolean[][][][] points, int y, int x, int ny, int nx){
		if(points[y][x][ny][nx] || points[ny][nx][y][x]){
			return false;
		}else{
			points[y][x][ny][nx] = true;
			points[ny][nx][y][x] = true;
			return true;
		}
	}

	public boolean check(int y, int x, int[] d){
		if(y + d[0] < 0 || y + d[0] > 10 || x + d[1] < 0 || x + d[1] > 10){
			return false;
		}
		return true;
	}

	public int solution(String dirs) {
		int answer = 0;
		boolean[][][][] points = new boolean[11][11][11][11];
		int[][] direction = {{-1,0}, {1,0}, {0,-1}, {0,1}}; // 상,하,좌,우
		Map<Character, Integer> map = new HashMap<>(){{
			put('U', 0);
			put('D', 1);
			put('L', 2);
			put('R', 3);
		}};
		int y = 5, x = 5, ny = 5, nx = 5;

		for(char c : dirs.toCharArray()){
			int[] d = direction[map.get(c)];

			if(!check(y, x, d)){
				continue;
			}

			ny += d[0];
			nx += d[1];

			if(move(points, y, x, ny, nx)){
				answer++;
			}

			y += d[0];
			x += d[1];
		}

		return answer;
	}
}