騎士巡遊問題演算法

來源:互聯網
上載者:User

騎士巡遊或叫馬步遍曆

問題描述:

在n*n的棋盤上,假設一個騎士按象棋中“馬”的走法,從初始座標(x1,y1)出發,要求無重複地走遍棋盤
中的每一個位置(每個點必須經過一次且只能是一次 )。請編寫程式,為騎士求解巡遊“路線”(或無解)。

代碼:

#include <iostream><br />#include <iomanip><br />using namespace std;<br />const int n = 5;//n*n的棋盤<br />int a[n+1][n+1];//二維數組表示棋盤,不使用0行0列<br />int move[9][3];//移動位移量(增量)。為方便起見,只使用其中1-8行、1-2列(不用0行0列)<br />bool possible;//是否擺放成功<br />void go(int i, int j, int k, bool &possible)<br />{<br />/*從(i,j)點出發,做第k至第n*n次的移動<br /> 若成功則通過引用參數q返回true*/<br />int v = 0,g,h;//v(取值1-8)表示方向,(g,h)表示從當前點(i,j)沿v方向移動後到達點的座標<br />do<br />{<br />v++;<br />possible = false;<br />g = i + move[v][1];<br />h = j + move[v][2];<br />if (g >= 1 && g <= n && h >= 1 && h <= n && a[g][h] == 0)//(g,h)處於棋盤內,且尚未放過棋子<br />{<br />a[g][h] = k;//將第k步棋子放在(g,h)點<br />if (k < n * n)//尚未放滿整個棋盤<br />{<br />go(g,h,k+1,possible);//遞迴調用<br />if(!possible)<br />a[g][h] = 0;<br />}<br />else//放滿整個棋盤,possible返回true<br />possible = true;<br />}<br />}<br />while(!possible && (v != 8));<br />}<br />int main()<br />{<br />//初始化move數組<br />move[1][1] = 2;move[1][2] = 1;<br />move[2][1] = 1;move[2][2] = 2;<br />move[3][1] = -1;move[3][2] = 2;<br />move[4][1] = -2;move[4][2] = 1;<br />move[5][1] = -2;move[5][2] = -1;<br />move[6][1] = -1;move[6][2] = -2;<br />move[7][1] = 1;move[7][2] = -2;<br />move[8][1] = 2;move[8][2] = -1;<br />cout << "Please input the first position:" << endl;<br />int x1,y1;<br />cin >> x1 >> y1;//輸入初始座標<br />a[x1][y1] = 1;//在棋盤(x1,y1)處放下棋子(第1步棋)<br />go(x1, y1, 2, possible);//從(x1,y1)出發,做第2至第25次的移動,若成功possible返回true<br />//若擺放成功,輸出棋盤(移動過程)<br />if (possible)<br />for (int i = 1; i <= n; i++)<br />{<br />for (int j = 1; j <= n; j++)<br />cout << setw(4) << a[i][j];<br />cout << endl;<br />}<br />else//擺放不成功<br />cout << "Impossible!" << endl;<br />return 0;<br />}

聯繫我們

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