Warnsdorff算法(骑士周游问题)

/*
 * File: KnightsTour.cpp
 * ---------------------
 * This program find a knight's tour on an N x M chessboard.
 */

#include "KnightsTour.h"

/*
 * Function: solveKnightsTour
 * Usage: solveKnightsTour(n, m);
 * ------------------------------
 * Solves the knight's tour problem for a n x m chessboard.
 */

void solveKnightsTour(int n, int m) {
   Grid<int> board(n, m);
   if (findKnightsTour(board, 0, 0, 1)) {
      displayBoard(board);
   } else {
      cout << "No tour exists for this board." << endl;
   }
}

/*
 * Function: displayBoard
 * Usage: displayBoard(board);
 * ---------------------------
 * Displays each of the squares in the board along with its sequence
 * number in the tour.
 */

void displayBoard(Grid<int> & board) {
   for (int i = board.numRows() - 1; i >= 0; i--) {
      for (int j = 0; j < board.numCols(); j++) {
         cout << " " << setw(2) << board[i][j];
      }
      cout << endl;
   }
}

vector< vector<int> > get_possibilities(Grid<int> & board, int x, int y, int n, int m) {
    vector<int> pos_x = {2, 1, -1, -2, -2, -1, 1, 2};
    vector<int> pos_y = {1, 2, 2, 1, -1, -2, -2, -1};
    vector< vector<int> > possibilities;
    for (int i = 0; i < 8; ++i) {
        if (x + pos_x[i] >= 0 && x + pos_x[i] <= n && y + pos_y[i] >= 0 && y + pos_y[i] <= m && board[x + pos_x[i]][y + pos_y[i]] == 0) {
            possibilities.push_back({x + pos_x[i], y + pos_y[i]});
        }
    }
    return possibilities;
}

bool findKnightsTour(Grid<int> & board, int row, int col, int seq) {
    int n = board.numRows() - 1;
    int m = board.numCols() - 1;
    board[row][col] = seq;
    seq = 2;
    for (int k = 0; k < (n + 1) * (m + 1) - 1; ++k){
        vector< vector<int> > pos = get_possibilities(board, row, col, n, m);
        if (pos.size() == 0) return false;
        vector<int> minimum = pos[0];
        for (unsigned long long i = 0; i < pos.size(); i++) {
            int Degree = get_possibilities(board, pos[i][0], pos[i][1], n, m).size();
            int MinDegree = get_possibilities(board, minimum[0], minimum[1], n, m).size();
            if (Degree <= MinDegree) {
                minimum = pos[i];
            }
        }
        row = minimum[0];
        col = minimum[1];
        board[row][col] = seq;
        ++seq;
    }
    return true;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值