递归方法,总是打印出相同的东西
recursive method ,always print out the same thing
#include<vector>
#include<iostream>
const int max = 8;
bool checkvalid(int* array, int row1, int col)
{
for(int j=0; j<row1; j++)
{
if( array[j] == col) //not in the same colon
return false;
if( ((row1- j) == ( array[j]-col)) || ((row1- j) == ( -array[j]+col)) ) // not in the same diagonal
return false;
}
return true;
}
void placequeen(int row, int* array, std::vector<int*> &myvector)
{
if( row == max)
{
myvector.push_back(array); // if I print here , result is correct
/* for(int i=0; i<8; i++)
std::cout << array[i] ;
std::cout << std::endl;*/
}
else
{
for(int i=0 ; i<max; i++)
{
if(checkvalid(array, row, i))
{
array[row] = i;
placequeen(row+1, array,myvector);
}
}
}
}
int main()
{
std::vector<int*> a;
int* array = new int[8];
placequeen(0, array, a);
for(std::vector<int*>::iterator it=a.begin(); it!=a.end(); it++)
{
for(int i=0 ; i<8; i++)
{
std::cout << (*it)[i] ; }
std::cout << std::endl;
}
}
这是破解密码面试的n皇后问题。它始终打印相同的结果"75346424"。但是,如果我在if(row==max(中打印,结果是正确的(我在那里切换代码(,为什么以及如何更改?感谢
从@Jarod42的评论中,我知道我必须将向量中的指针更改为std::数组。在我以前的代码中,我一次又一次地将相同的指针存储在向量中。#包括#包括
const int max = 8;
bool checkvalid(std::array<int, 8> array, int row1, int col) // change array* to std::array<int, 8> array
{
for(int j=0; j<row1; j++)
{
if( array[j] == col) //not in the same colon
return false;
if( ((row1- j) == ( array[j]-col)) || ((row1- j) == ( -array[j]+col)) ) // not in the same diagonal
return false;
}
return true;
}
void placequeen(int row, std::array<int, 8> array, std::vector<std::array<int, 8>> &myvector) // change array* to std::array<int, 8> array
{
if( row == max)
{
myvector.push_back(array); // if I print here , result is correct
}
else
{
for(int i=0 ; i<max; i++)
{
if(checkvalid(array, row, i))
{
array[row] = i;
placequeen(row+1, array,myvector);
}
}
}
}
int main()
{
std::vector<std::array<int, 8>> a;
std::array<int, 8> array;
placequeen(0, array, a);
for(std::vector<std::array<int, 8>>::iterator it=a.begin(); it!=a.end(); it++)
{
for(int i=0 ; i<8; i++)
{
std::cout << (*it)[i] ; }
std::cout << std::endl;
}
}
相关文章:
- C++:正在检查LinkedList中的回文-递归方法-错误
- 数组元素打印的递归方法
- 我对 leetcode 72 上的递归方法感到茫然
- 使用递归方法遇到分段错误
- 我的链接列表反向递归方法的代码的问题是什么?
- 在链接列表中找到值的递归方法
- 如何打印递归 lambda 模板的名称
- 我应该如何实现递归方法以找到在C++中形成最大堆的多种方法
- 使用递归方法将矢量作为输入时进行分割故障
- 使用递归方法的类,使用int矢量元素作为输入
- 3D 迷宫递归方法 - C++
- 这种遍历二叉树的递归方法在一些递归后崩溃!为什么?
- 迭代器回到递归方法的开头
- 如何创建一个递归方法来比较两个值
- 为什么将十进制转换为二进制的递归方法比迭代、使用和返回字符串更快
- 递归方法中的 C++ 凸包
- 如何将查找组合的几个循环代码转换为递归方法
- 删除单向链表最后一个元素的递归方法
- 反转字符串的递归方法
- 递归方法,总是打印出相同的东西