一馬當(dāng)先,C++ 之解法

一馬當(dāng)先是一道經(jīng)典的動(dòng)態(tài)規(guī)劃問題, 今天狐狐嘗試用C++來解此題:

下過象棋的人都知道,馬只能走'日'字形(包括旋轉(zhuǎn)90°的日),現(xiàn)在想象一下,給你一個(gè)n行m列網(wǎng)格棋盤,棋盤的左下角有一匹馬,請(qǐng)你計(jì)算至少需要幾步可以將它移動(dòng)到棋盤的右上角,若無法走到,則輸出-1. 如n=1,m=2,則至少需要1步;若n=1,m=3,則輸出-1。

解法一(Solution1):

使用vector創(chuàng)建動(dòng)態(tài)二維數(shù)組

#include <vector>
#include <iostream>

using namespace std;

void step_board(int n, int m) {vector> board(n+1, vector(m+1));

for (int i = 0; i < n + 1; i++) {

for (int j = 0; j < m + 1; j++)

{

board[i][j] = -1;

}

}

board[0][0] = 0;

int r[] = { -1, -2, -2, -1, 1, 2, 2, 1 };

int c[] = { -2, -1, 1, 2, 2, 1, -1, -2 };

int flag = 1;

while (flag == 1) {

flag = 0;

for (int row = 0; row < n + 1; row++) {

for (int col = 0; col < m + 1; col++) {

if (board[row][col] == -1) {

int minstep = 1000000;

for (int i = 0; i < 8; i++) {

if (row + r[i] >= 0 && row + r[i] < n + 1 && col + c[i] >= 0

&& col + c[i] < m + 1 && board[row + r[i]][col + c[i]] >= 0

&& board[row + r[i]][col + c[i]] < minstep) {

minstep = board[row + r[i]][col + c[i]] + 1;

}

}

if (minstep < 1000000) {

board[row][col] = minstep;

flag = 1;

}

}

}

}

}

cout << "The least step:" << to_string(board[n][m]) << endl;

}

解法二(Solution2):

使用指針pointer創(chuàng)建動(dòng)態(tài)二維數(shù)組

#include <iostream>

using namespace std;

void step_board(int n, int m) {

int **board = new int*[n];

for (int i = 0; i < n + 1; i++){

board[i] = new int[m];

}

for (int i = 0; i < n + 1; i++) {

for (int j = 0; j < m + 1; j++)

{

board[i][j] = -1;

}

}

board[0][0] = 0;

int r[] = { -1, -2, -2, -1, 1, 2, 2, 1 };

int c[] = { -2, -1, 1, 2, 2, 1, -1, -2 };

int flag = 1;

while (flag == 1) {

flag = 0;

for (int row = 0; row < n + 1; row++) {

for (int col = 0; col < m + 1; col++) {

if (board[row][col] == -1) {

int minstep = 1000000;

for (int i = 0; i < 8; i++) {

if (row + r[i] >= 0 && row + r[i] < n + 1 && col + c[i] >= 0

&& col + c[i] < m + 1 && board[row + r[i]][col + c[i]] >= 0

&& board[row + r[i]][col + c[i]] < minstep) {

minstep = board[row + r[i]][col + c[i]] + 1;

}

}

if (minstep < 1000000) {

board[row][col] = minstep;

flag = 1;

}

}

}

}

}

cout << "The least step:" << to_string(board[n][m]) << endl;

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容