Last active
August 13, 2019 05:56
-
-
Save sreeprasad/5530a192a0db15be7f428a5ecfd66be8 to your computer and use it in GitHub Desktop.
Minimum number of moves
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void find(N,M) { | |
boolean [][] visited = new boolean[100000][1000]; | |
int [][] cache = new int[100000][13]; | |
int ans = dfs(N, visited, cache, 0, M); | |
if(ans>N) ans = -1; | |
System.out.printf("%d\n", ans); | |
} | |
private int dfs(int N, boolean[][]visited, int [][] cache, int moves, int M) { | |
if(N==0) { | |
if(moves!=0) return 10000000;// return big number bec we want to find min number of moves | |
else return 0; | |
} | |
if (visited[N][moves]) return cache[N][moves]; | |
visited[N][moves] = true; | |
int m1 = dfs(N-1, visited, cache, (moves+1)%M, M); | |
int m2 = Integer.MAX_VALUE; | |
// dont calcualte steps required when N>1 because otherwise dfs(N-2,...) will be find number of moves for N<0. | |
// we dont want moves when N<0. We only want to calcualte moves up to N=0; | |
if (N>1) { | |
m2 = dfs(N-2, visited, cache, (moves+1)%M, M); | |
} | |
int ans = Math.min(m2, m1); | |
cache[N][moves]= ans+1; | |
return cache[N][moves]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment