递归方法,总是打印出相同的东西

recursive method ,always print out the same thing

本文关键字:打印 递归方法      更新时间:2023-10-16
#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;
  }
}