JUMPGAME (java) - 시간초과 해결 가능할까요?

  • dsj
    dsj

    java로 동적계획법 사용하여 코드 작성했습니다.
    정답은 잘 출력되는 듯 한데, 답안제출 시 시간초과가 뜨네요..
    시간 줄일 수 있는 방법 알 수 있을까요!

    import java.util.Arrays;
    import java.util.Scanner;
    
    public class Main {
        static int n;
        static int[][] num;
        static int[][] cache;
        public static int jump(int x, int y)
        {   
            if(x > n || y > n)
                return 0;
            else if (x == n && y == n)
                return 1;
            else
            {
                int a = num[x-1][y-1];
                int ret = cache[x-1][y-1];
                if(ret != -1)
                    return ret;
                else
                    return ret = jump(x+a,y) + jump(x,y+a);
            }
        }
        public static void main(String[] args) 
        {
            Scanner sc = new Scanner(System.in);
            int TC = sc.nextInt();
            for(int test_case=0; test_case<TC; test_case++)
            {
                n = sc.nextInt();
                num = new int[n][n];
                cache = new int[n][n];
    
                for(int i=0; i<n; i++)
                {
                    Arrays.fill(cache[i], -1);
                    for(int j=0; j<n; j++)
                    {
                        num[i][j] = sc.nextInt();
                    }
                }
    
                if(jump(1,1) != 0)
                    System.out.println("YES");
                else
                    System.out.println("NO");
            }
        }
    
    }
    

    7년 전
1개의 댓글이 있습니다.
  • BadCandy
    BadCandy

    코드를 보시면 JAVA와 C++을 햇갈려 하시는 것 같습니다. C++에서는 참조 변수를 이용하여 cache[][]의 값을 바꿀수 있지만 자바의 경우는 직접 cache[][]의 값을 바꿔주셔야 합니다. 직접 바꿔주시지 않는 경우 cache를 이용하는 이유가 없겠죠..?


    7년 전 link
  • 정회원 권한이 있어야 커멘트를 다실 수 있습니다. 정회원이 되시려면 온라인 저지에서 5문제 이상을 푸시고, 가입 후 7일 이상이 지나셔야 합니다. 현재 문제를 푸셨습니다.