编程题1
题目描述:寻找一条从左上角arr[0][0]到右下角arr[m-1][n-1]的路线,使得沿途经过的数组中的整数之和最小
代码:
java版实现:
01 02 03 04 05 06 07 08 09 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 | public class FindRoute { public static int getMinPath( int [][] arr){ if (arr == null || arr.length == 0 ){ return 0 ; } int row = arr.length; int col = arr[ 0 ].length; // 用来保存计算的中间值 int [][] cache = new int [row][col]; cache[ 0 ][ 0 ] = arr[ 0 ][ 0 ]; for ( int i = 1 ; i < col; i++){ cache[ 0 ][i] = cache[ 0 ][i - 1 ] + arr[ 0 ][i]; } for ( int j = 1 ; j < row; j++){ cache[j][ 0 ] = cache[j - 1 ][ 0 ] + arr[j][ 0 ]; } System.out.println( "[" +( 0 )+ "," + 0 + "]: " + arr[ 0 ][ 0 ]); // 在遍历二维数组的过程中不断把计算结果保存到cache中 for ( int i = 1 ; i < row; i++){ for ( int j = 1 ; j < col; j++){ if (cache[i - 1 ][j] > cache[i][j - 1 ]){ // 可以确定选择的路线为arr[i][j - 1] cache[i][j] = cache[i][j - 1 ] + arr[i][j]; System.out.println( "[" +i+ "," +(j - 1 )+ "]: " + arr[i][j - 1 ]); } else { // 可以确定选择的路线为arr[i - 1][j] cache[i][j] = cache[i - 1 ][j] + arr[i][j]; System.out.println( "[" +(i - 1 )+ "," +j+ "]: " + arr[i - 1 ][j]); } } } System.out.println( "[" +(row - 1 ) + "," + (col - 1 ) + "]" + arr[row - 1 ][col - 1 ]); return cache[row - 1 ][col - 1 ]; } public static void main(String[] args){ int [][] arr = { { 1 , 4 , 3 , 3 }, { 8 , 7 , 5 , 5 }, { 2 , 1 , 5 , 5 }, { 2 , 1 , 5 , 5 } }; System.out.println( "路径:" ); System.out.println( "最小值为:" +getMinPath(arr)); } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步