演算法筆記_135:格子取數問題(Java)

來源:互聯網
上載者:User

標籤:解決方案   for   java   logs   面試   void   test   imp   str   

目錄

1 問題描述

2 解決方案

  1 問題描述

有n*n個格子,每個格子裡有正數或者0,從最左上方往最右下角走,只能向下和向右走,一共走兩次(即從左上方往右下角走兩趟),把所有經過的格子裡的數加起來,求總和的最大值。如果兩次經過同一個格子,則最後求得的總和中該格子中的數只加一次。

  2 解決方案

此處採用動態規劃法,可以較大的提高時間效率。

具體代碼如下:

 

package com.liuzhen.practice;import java.util.Scanner;public class Main {        public boolean judge(int s, int i ,int j ,int len) {        int x1 = 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 int getValue(int[][][] dp, int s, int i , int j, int len) {        if(judge(s, i, j, len))            return dp[s][i][j];        return -1;    }        public void getResult(int[][] value) {        int len = value.length;        int[][][] dp = new int[len * 2][len][len];        dp[0][0][0] = value[0][0];        for(int s = 1;s <= len * 2 - 2;s++) {            for(int i = 0;i < len;i++) {                for(int j = 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];                        else                            dp[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 void main(String[] args) {        Main test = new Main();        Scanner in = new Scanner(System.in);        int n = in.nextInt();        int[][] value = new int[n][n];        for(int i = 0;i < n;i++)            for(int j = 0;j < n;j++)                value[i][j] = in.nextInt();        test.getResult(value);    }}

 

運行結果:

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

 

 

 

 

 

參考資料:

   1.《編程之法面試和演算法心得》  July 著

 

演算法筆記_135:格子取數問題(Java)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.