如何解决试图解决嵌套 vector<vector<pair<int,int>> 上的 Knights Tour 但不起作用
我为骑士之旅问题编写了一个代码,它适用于二维数组但不适用于 vector<vector<pair<int,int>>
工作代码
#include <bits/stdc++.h>
#define N 8
using namespace std;
bool isPossible(int sol[N][N],int x,int y)
{
if ( sol[x][y]==-1 && x >= 0 && x < N && y >= 0 && y < N)
{
return true;
}
return false;
}
bool KNT(int sol[N][N],int moveNUM,int y,int movex[8],int movey[8])
{
int i,next_x,next_y;
if (moveNUM == N * N)
{
return true;
}
for ( i = 0; i < 8; i++)
{
next_x = x + movex[i];
next_y = y + movey[i];
if (isPossible(sol,next_y))
{
sol[next_x][next_y]=moveNUM;
if (KNT(sol,moveNUM + 1,next_y,movex,movey))
{
return true;
}
sol[next_x][next_y] = -1; //Backtracking
}
}
return false;
}
int main()
{
int sol[N][N];
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
sol[i][j]=-1;
}
}
int movex[8] = {2,1,-1,-2,2};
int movey[8] = {1,2,-1};
KNT(sol,movey);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
cout << sol[i][j] << " ";
}
cout << endl;
}
}
非工作代码
#include <bits/stdc++.h>
#define N 8
using namespace std;
bool isPossible(vector<vector<pair<int,int>>> &Brd,int y)
{
if ((Brd[x][y].first == -1) && x >= 0 && x < N && y >= 0 && y < N)
{
return true;
}
return false;
}
bool KNT(vector<vector<pair<int,next_y;
if (moveNUM == N * N)
{
return true;
}
for ( i = 0; i < 8; i++)
{
next_x = x + movex[i];
next_y = y + movey[i];
if (isPossible(Brd,next_y))
{
Brd[next_x][next_y].first = 1;
Brd[next_x][next_y].second = moveNUM;
if (KNT(Brd,movey))
{
return true;
}
Brd[next_x][next_y].first = -1;
Brd[next_x][next_y].second = 0;
//Backtracking
}
}
return false; //Check for error
}
int main()
{
vector<vector<pair<int,int>>> Brd;
for (int i = 0; i < N; i++)
{
vector<pair<int,int>> temp;
for (int j = 0; j < N; j++)
{
temp.push_back(make_pair(-1,0));
}
Brd.push_back(temp);
}
int movex[8] = {2,-1};
KNT(Brd,movey);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
cout << Brd[i][j].second << " ";
}
cout << endl;
}
}
在非工作代码中,当我运行代码时,它不会给出任何输出,而是突然结束。
附言任何帮助都将意味着很多我已经浪费了大约 2 天的时间来寻找解决方案。
解决方法
两个程序都有未定义的行为,因为您访问的二维数组/向量越界。
您首先检查是否 sol[x][y] == -1
,然后检查 x
和 y
是否在边界内:
bool isPossible(int sol[N][N],int x,int y)
{
if (sol[x][y]==-1 && x >= 0 && x < N && y >= 0 && y < N)
您需要先检查边界。
您的第一个解决方案应该:
if (x >= 0 && x < N && y >= 0 && y < N && sol[x][y]==-1)
您的第二个解决方案应该:
if(x >= 0 && x < N && y >= 0 && y < N && Brd[x][y].first == -1)
注意:这两个程序产生不同的解决方案。您必须决定哪一个是正确的(如果有)。
首先:
-1 59 38 33 30 17 8 63
37 34 31 60 9 62 29 16
58 1 36 39 32 27 18 7
35 48 41 26 61 10 15 28
42 57 2 49 40 23 6 19
47 50 45 54 25 20 11 14
56 43 52 3 22 13 24 5
51 46 55 44 53 4 21 12
第二:
0 59 38 33 30 17 8 63
37 34 31 60 9 62 29 16
58 1 36 39 32 27 18 7
35 48 41 26 61 10 15 28
42 57 2 49 40 23 6 19
47 50 45 54 25 20 11 14
56 43 52 3 22 13 24 5
51 46 55 44 53 4 21 12
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。