[Programmers] 방문 길이 - Summer/Winter Coding(~2018)

동민·2021년 3월 11일
import java.util.ArrayList;

// 방문 길이 - Summer/Winter Coding(~2018)
public class VisitLength {
	private static ArrayList<String> list; // 좌표를 String으로 ("x1y1,x2y2") 판단하여 지나간 길을 list에 저장 
	public int solution(String dirs) {
		
		list = new ArrayList<>();
		char[] d = dirs.toCharArray();
		int x = 0, y = 0;

		for (char ele : d) {
			String xyxy = "";
			if(ele == 'U' && isValid(x, y + 1)){
                xyxy = Integer.toString(x)+Integer.toString(y) + "," + Integer.toString(x) + Integer.toString(++y);
            }else if(ele == 'D' && isValid(x, y - 1)){
                xyxy = Integer.toString(x)+Integer.toString(y) + "," + Integer.toString(x) + Integer.toString(--y);
            }else if(ele == 'L'&& isValid(x-1, y)){
                xyxy = Integer.toString(x)+Integer.toString(y) + "," + Integer.toString(--x) + Integer.toString(y);
            }else if(ele == 'R'&& isValid(x+1, y)){
                xyxy = Integer.toString(x)+Integer.toString(y) + "," + Integer.toString(++x) + Integer.toString(y);
            }else{
                continue; // isValid()에서 false를 리턴했을 때, 아래 if( isContain(xyxy) ) { list.add(xyxy); } 이부분을 실행하지 않도록 continue 처리
            }
			
			if (isContain(xyxy)) {
				list.add(xyxy);
			}
		}
		
		return list.size();
	}

	private boolean isContain(String xyxy) { // "x1y1,x2y2", "x2y2,x1y1" 두 좌표가 list에 포함되어있는지 체크; 지나간 길은 "x1y1,x2y2" == "x2y2,x1y1"이기 때문
		String rotateXY = xyxy.split(",")[1] + "," + xyxy.split(",")[0];
		return list.contains(xyxy) || list.contains(rotateXY) ? false : true;
	}

	private boolean isValid(int x, int y) { // 좌표 범위를 벗어났는지 체크
		return x <= 5 && x >= -5 && y <= 5 && y >= -5 ? true : false;
	}
}
profile
BE Developer

0개의 댓글