강의

멘토링

로드맵

Inflearn brand logo image

인프런 커뮤니티 질문&답변

tkv00님의 프로필 이미지
tkv00

작성한 질문수

자바 코딩테스트 - it 대기업 유제

비밀번호

작성

·

15

·

수정됨

0

package 인프런.시뮬레이션_복습01;

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

public class 비밀번호 {
    public static class Point{
        int row;
        int col;
        Point(int row,int col){
            this.row=row;
            this.col=col;
        }
    }

    private static Map<Integer,Point> map;
    private static final int INF=3;
    private static int getDistance(int row1,int col1,int row2,int col2){
        return (int)Math.pow(row1-row2,2) + (int)Math.pow(col1-col2,2);
    }
    private static boolean isValid(int dis){
        //거리가 대각선 포함 이동시간이 1인 경우
        if(dis<=2) return true;
        return false;
    }
    static class Solution {
        public int solution(int[] keypad, String password){
            int time = 0;
            map=new HashMap<>();

            for(int i=0;i<INF*INF;i++){
                map.put(keypad[i],new Point(i/3,i%3));
            }
            String[] inputs=password.split("");
            /**
             * 시작 값 초기화
             */
            int nowX=map.get(Integer.parseInt(inputs[0])).row,nowY=map.get(Integer.parseInt(inputs[0])).col;

            for(int i=1;i<inputs.length;i++){
                int x=Integer.parseInt(inputs[i]);
                int nRow=map.get(x).row;
                int nCol=map.get(x).col;

                if(nowX==nRow && nowY==nCol) continue;
                if(isValid(getDistance(nowX,nowY,nRow,nCol))){
                    time++;
                }else{
                    time+=2;
                }
                nowX=nRow;
                nowY=nCol;
            }


            return time;
        }

        public static void main(String[] args){
            Solution T = new Solution();
            System.out.println(T.solution(new int[]{2, 5, 3, 7, 1, 6, 4, 9, 8}, "7596218"));
            System.out.println(T.solution(new int[]{1, 5, 7, 3, 2, 8, 9, 4, 6}, "63855526592"));
            System.out.println(T.solution(new int[]{2, 9, 3, 7, 8, 6, 4, 5, 1}, "323254677"));
            System.out.println(T.solution(new int[]{1, 6, 7, 3, 8, 9, 4, 5, 2}, "3337772122"));
        }
    }
}

해시맵을 사용하여 풀었는데 이 방법도 시간 복잡도 혹은 공간 복잡도면에서 괜찮나요??

답변

답변을 기다리고 있는 질문이에요
첫번째 답변을 남겨보세요!
tkv00님의 프로필 이미지
tkv00

작성한 질문수

질문하기