Directory
1 Problem Description
2 Solutions
1 problem description
There are n*n , each lattice has a positive number or 0, from the top left corner to the bottom right corner, can only go down and to the right, a total of two times ( that is, from the upper left to the lower right corner of the walk two times ), add up the number of all the squares that pass through, and find the maximum value of the sum. If two passes through the same lattice, then the number in the last calculated sum is only added once.
2 Solutions
The dynamic programming method is used here to improve the time efficiency greatly.
The specific code is as follows:
PackageCom.liuzhen.practice;ImportJava.util.Scanner; Public classMain { Public BooleanJudgeintSintIintJintLen) { intx1 = s-i, x2 = S-J; if(x1 >= 0 && x1 < len && x2 >= 0 && x2 < len && I >= 0 && J >= 0 && i < Len && J <len)return true; return false; } Public intGetValue (int[][][] DP,intSintIintJintLen) { if(judge (S, I, J, Len))returnDp[s][i][j]; return-1; } Public voidGetResult (int[] value) { intLen =value.length; int[][][] dp =New int[Len * 2][len][len]; dp[0][0][0] = value[0][0]; for(ints = 1;s <= len * 2-2;s++) { for(inti = 0;i < len;i++) { for(intj = 0;j < len;j++) { if(judge (S, I, J, Len)) {if(I! =j) Dp[s][i][j]= Math.max (Math.max (GetValue (Dp,s-1,i-1,j-1,len), GetValue (dp,s-1, I,j,len)), Math.max (GetValue (Dp,s-1,i-1,j,len), GetValue (Dp,s-1,i,j-1,len)) + Value[i][s-i] + value[j][s-J]; ElseDp[s][i][j]= Math.max (GetValue (dp,s-1,i-1,j-1, Len), Math.max (GetValue (Dp,s-1,i-1,j,len), GetValue (Dp,s-1,i,j,len)) + value[i][s-i]; }}}} System.out.println (dp[2 * len-2][len-1][len-1]); return; } Public Static voidMain (string[] args) {main test=NewMain (); Scanner in=NewScanner (system.in); intn =In.nextint (); int[] Value =New int[N][n]; for(inti = 0;i < n;i++) for(intj = 0;j < n;j++) Value[i][j]=In.nextint (); Test.getresult (value); }}
Operation Result:
60 0 3 0 2 00 0 3 0 0 00 0 3 0 0 00 0 0 0 4 00 0 0 0 4 00 0 3 0 0 02280 0 0 0 0 0 0 00 0 13 0 0 6 0 00 0 0 0 7 0 0 00 0 0 14 0 0 0 00 21 0 0 0 4 0 00 0 15 0 0 0 0 00 14 0 0 0 0 0 00 0 0 0 0 0 0 067
Resources:
1."Programming method interview and algorithmic experience" July
Algorithm Note _135: Lattice fetch number problem (Java)