Warnsdorff为骑士之旅的算法

时间:2017-06-15 19:43:55

标签: c++ algorithm c++11

请帮我这个代码。我不知道为什么不打印输出。该代码基于Warnsdorff的Knight巡演问题算法。它说" [错误]:Id返回1退出状态。当我在线执行它时,它会出现运行时错误。请帮助优化我的代码。

#include <bits/stdc++.h>
#define n 8
using namespace std;

static int x_move[n] = {2, 2, -1, -1, 1, 1, -2, -2};
static int y_move[n] = {1, -1, 2, -2, 2, -2, 1, -1};

void print(int arr[][n]) {
    for (int i = 0 ; i < n ; ++i) {
        for (int j = 0 ; j < n ; ++j)
            cout<<arr[i][j]<<" ";
        cout<<"\n";
    }
}

bool safe(int arr[][n] , int r , int c) {
    return (r >= 0 && c >= 0 && r < n && c < n && arr[r][c] == -1);
}

bool neighbour(int r , int c , int sr , int sc) {
    for (int i = 0 ; i < n ; ++i)
        if ((r + x_move[i] == sr) && (c + x_move[i] == sc))
            return true;
    return false;
}

int depth(int arr[][n] , int r , int c) {
    int co = 0;
    for (int i = 0 ; i < n ; ++i)
        if (safe(arr , r + x_move[i] , c + y_move[i]))
            c++;
    return c;
} 

bool next_one(int arr[][n] , int *r , int *c) {
    int nr , nc; 
    int min_dep_index = -1;
    int min_dep = n + 1;
    int k;
    int s = rand() % n;
    for (int co = 0 ; co < n ; ++co) {
        int i = (s + co) % n;
        nr = *r + x_move[i];
        nc = *c + y_move[i];
        k = depth(arr , nr , nc);
        if (safe(arr , *r , *c) && k < min_dep) {
            min_dep_index = i;
            min_dep = k;
        }
    }
    if (min_dep_index == -1)
        return false;
    nr = *r + x_move[min_dep_index];
    nc = *c + y_move[min_dep_index];
    arr[nr][nc] = arr[*r][*c] + 1;
    *r = nr;
    *c = nc;
    return true;
}

bool foo(int arr[][n]) {
    for (int i = 0 ; i < n ; ++i)
        for (int j = 0 ; j < n ; ++j)
            arr[i][j] = -1;
    int r , c , sr , sc;
    sc = rand() % n;
    sr = rand() % n;
    r = sr;
    c = sc;
    arr[r][c] = 1;
    for (int i = 0 ; i < n*n ; ++i) {
        if (next_one(arr , &r , &c) == false)
            return false;
    }
    if (!neighbour(r , c , sr , sc))
        return false;
    print(arr);
    return true;
}

int main() {
    int arr[n][n];
    srand(time(nullptr));
    while (foo(arr) == false) {
    ;
    }
    return 0;
}

0 个答案:

没有答案