骑士走盘问题

#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

#define ROW 5
#define COL 5

bool traverse(vector<vector<int> > &result, vector<vector<int> > &board, int x, int y, int count)
{

        board[x][y] = count;
        if(count >= ROW * COL)
        {
            result = board;
            return true;
        }

        int dy[8] = {2,  2, 1, -1, -2, -2, -1, 1}; //
        int dx[8] = {-1, 1, 2, 2, 1,  -1, -2, -2}; //
        for(int i = 0; i < 8; i++)
        {
                int nx = x + dx[i];
                int ny = y + dy[i];
                if(nx <0 || nx >= COL || ny < 0 || ny >= ROW)
                {
                        continue;
                }

                if(board[nx][ny] != 0) // already traversed
                {
                        continue;
                }

                //go next
                traverse(result, board, nx, ny, count+1);
        }
        board[x][y] = 0;
        return true;
}
void printBoard(vector<vector<int> > &board)
{
        for(int i = 0; i < board.size(); i++)
        {
                for(int j = 0; j < board[i].size(); j++)
                {
                        cout<<setw(4)<<board[i][j]<< " ";
                }
                cout<<endl;
        }
}
int main(void)
{
        vector<vector<int> > board(ROW, vector<int>(COL, 0));
        vector<vector<int> > result(ROW, vector<int>(COL, 0));
        int start_x = 0;
        int start_y = 0;
        cout<<"Please input start point:"<<endl;
        cin>>start_x>>start_y;
        cout<<"Start from ["<<start_x<<","<<start_y<<"]"<<endl;
        bool ok = traverse(result, board, start_x, start_y, 1);
        if(ok)
        {
            printBoard(result);
        }
        else
        {
           cout<<"Unable to traverse all cells"<<endl;
        }
        return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值