馬的問題

#include "iostream"
#include "iomanip"
#include "cstdlib"
using namespace std;

int board[100][100];
int dx[8] = {-2, -1, 1,  2, -2, -1, 2, 1};  //馬可走的八個方向
int dy[8] = {-1, -2, -2, -1, 1,  2, 1, 2};
int n, m;  //棋盤爲m * n
int startx, starty;  //馬的起點座標

//如果座標出界,或該棋盤格已走過,則返回0,否則返回1
int ok(int x, int y)
{
    if(x<1 || y<1 || x>m || y>n || board[x][y]!=0)
        return 0;
    return 1;
}

//打印路線
void print(int n, int m)
{
    for(int i=1; i<=m; i++)
    {
        for(int j=1; j<=n; j++)
            cout << setw(3) << board[i][j];
        cout << endl;
    }
}

int restart(int x, int y)  //判斷下一步是否可以回到起點
{
    for(int i=0; i<8; i++)
        if(x+dx[i]==startx && y+dy[i]==starty)
            return 1;
    return 0;
}

void backtrack(int x, int y, int count)
{
    if(count == n * m && restart(x, y))  //如果走完棋盤,且回到起點
    {
        print(n, m);
        exit(1);
    }
    for(int i=0; i<8; i++)  //每到一個格子,都有八個方向
    {
        int xx = x + dx[i];
        int yy = y + dy[i];
        if(ok(xx, yy))  //如果座標正常
        {
            board[xx][yy] = count + 1;
            backtrack(xx, yy, count + 1);
            board[xx][yy] = 0;  //回溯
        }
    }
}

int main()
{
    cout << "輸入棋盤行數:";
    cin >> m;
    cout << "輸入棋盤列數:";
    cin >> n;
    memset(board, 0, sizeof(board));
    cout << "輸入馬的起始座標:";
    cin >> startx >> starty;
    board[startx][starty] = 1;
    int number = 1;
    cout << "路線爲:\n";
    backtrack(startx, starty, number);
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章