【问题标题】:Fixing input problems in C++ for reference variables修复 C++ 中引用变量的输入问题
【发布时间】:2021-04-03 19:42:16
【问题描述】:
bool isSafe(char arr[][N],int r,int c)
{
//to check that queens are not in the same column
for(int i=0;i<=r;i++){
if(arr[i][c]=='Q')
return false;}

//to check that queens are not in the same left diagonal
for(int i=r,j=c;i>=0&&j>=0;i--,j--){
if(arr[i][j]=='Q')
return false;}

//to check that queens are not in the same right diagonal
for(int i=r,j=c;i>=0&&j<N;i--,j++){
if(arr[i][j]=='Q')
return false;}
}

这是 N Queens 问题的代码的一部分,我使用#define N 8N 定义为 8 现在,以下是 -

cout<<"The solution(s) are-"<<endl;
char arr[N][N];
memset(arr,'-',sizeof arr);         //initializes the entire n*n chessboard with '-'
solveNQueen(arr,0);

这是在 ma​​in 功能下。但在这里,我最初将 N 定义为一个常数,等于 8。我不能在 ma​​in 下寻找可能的输入语句(N),因为这会导致 @987654324 中的 N 范围问题@那么在这种情况下,我应该怎么做才能让用户通过终端输入N的值,而不会出现任何问题?

【问题讨论】:

    标签: c++ arrays scope iostream


    【解决方案1】:

    简单的解决方案是使用向量。

    int n;
    cin >> n;
    vector<vector<char>> v(n, vector<char>(n));
    solveNQueen(v, 0);
    
    bool isSafe(vector<vector<char>>& v,int r,int c)
    {
        int n = v.size();
        ...
    }
    

    如果您需要知道向量的大小,可以使用 size 方法得到它,v.size();

    【讨论】:

      猜你喜欢
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多