-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPaths to reach origin .txt
54 lines (54 loc) · 1.31 KB
/
Paths to reach origin .txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main (String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringBuffer sb=new StringBuffer();
int T=Integer.parseInt(br.readLine());
while(T-->0)
{
String[] s=br.readLine().split("\\s");
int m=Integer.parseInt(s[0]);
int n=Integer.parseInt(s[1]);
int[][] dp=new int[m+1][n+1];
for(int i=0;i<m+1;i++)
{
for(int j=0;j<n+1;j++)
{
dp[i][j]=-1;
}
}
sb.append(solve(m,n,m,n,dp)+"\n");
}
System.out.print(sb);
}
public static int solve(int m,int n,int posx,int posy,int[][] dp)
{
if(posx==0 && posy==0)
{
return 1;
}
if(dp[posx][posy]!=-1)
{
return dp[posx][posy];
}
int smallans1=0,smallans2=0;
if(canplace(m,n,posx-1,posy))
{
smallans1=solve(m,n,posx-1,posy,dp);
}
if(canplace(m,n,posx,posy-1))
{
smallans2=solve(m,n,posx,posy-1,dp);
}
dp[posx][posy]=smallans1+smallans2;
return dp[posx][posy];
}
public static boolean canplace(int m,int n,int posx,int posy)
{
return posx>=0 && posy>=0;
}
}