演算法導論-15-6-在棋盤上移動

來源:互聯網
上載者:User

題目:

思考:

用一個矩陣s來儲存N*N的棋盤,用ans來儲存中間過程

(1)初始化:ans[i][j] = s[i][j] (i = N)

(2)遞推:ans[i][j] = MAX(s[i+1][j-1], s[i+1][j], s[i+1][j+1]) + s[i][j] (1<=i<N)

(3)結果:answer = MAX(s[i][j]) (i = 1)

代碼:

#include <iostream>using namespace std;#define N 10//為了便於處理邊界問題int map[N+2][N+2];int max(int a, int b, int c){if(a > b)return a > c ? a : c;elsereturn b > c ? b : c;}int main(){int i, j, n;while(cin>>n){memset(map, 0, sizeof(map));//產生隨機測試資料for(i = 1; i <= n; i++){for(j = 1; j <= n; j++){//cin>>map[i][j];map[i][j] = rand() % 10 - 5;cout<<map[i][j]<<' ';}cout<<endl;}int MAX = -0x7fffffff;//數組s與數組ans合并為數組map//ans[i][j] = s[i][j] (i = N)for(i = n-1; i >= 1; i--){for(j = 1; j <= n; j++){//ans[i][j] = MAX(s[i+1][j-1], s[i+1][j], s[i+1][j+1]) + s[i][j] (1<=i<N)map[i][j] = map[i][j] + max(map[i+1][j-1], map[i+1][j], map[i+1][j+1]);//answer = MAX(s[i][j]) (i = 1)if(i == 1 && map[i][j] > MAX)MAX = map[i][j];}}cout<<MAX<<endl;}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.