0

ネストされたいくつかのwhileループから抜け出そうとしていますが、問題が発生しています。このプログラムを、特定の回数だけ実行される外側のループに分割してほしい。ブール値で試してみましたが、プログラムの終了が早すぎます。これは、1x1、2x2、3x3、...nxnクイーンを解決しているNクイーンの問題です。

これが私のコードです:

bool ok(int *q, int col)
{
   for(int i=0; i<col; i++)
      if(q[col]==q[i] || (col-i)==abs(q[col]-q[i])) return false;

return true;
};

void print(int q[], int n, int cnt)
{
    //static int count =0;
    cout<<"There are "<<cnt<<" solutions for "<<n<<" queens." <<endl;   
};

int main()
{
    int n;
    int *q;
    cout<<"Please enter the size of the board:"<<endl;
    cin>>n;

    int static count = 0;

    int c = 1;
    int a = 1;
    bool from_backtrack=false;

    while(a!=n){

        q= new int[a];
        q[0]=0;
        bool foundSolution=true;
        while(foundSolution)
        {
            if (c==a){
                a++;
            }
            while(c<a)
            {
                if(!from_backtrack)
                    q[c] = -1; //Start at the top
                from_backtrack=false;
                while(q[c]<a)
                {
                    q[c]++;
                    if  (q[c]==a)
                    {
                        c--;
                        if(c==-1) {
                            print(q, n, count);
                            foundSolution=false;
                            //system("PAUSE"); exit(1);
                        }
                        continue;
                    }
                    if( ok(q,c) ) break; //get out of the closest while loop
                }
                c++;
            }
            count++;
            c--;
            if(c==-1) {
                print(q, n, count);
                foundSolution=false;
                //system("PAUSE"); exit(1);
            }
            from_backtrack=true;
        }
        delete[a] q;
        a++;
    }
    system("PAUSE");
}
4

4 に答える 4

2

The most elegant way would be to wrap some of your inner loops in a function. It will be easier to read and to control.

于 2013-03-13T23:06:54.103 に答える
0

At my work, we employ MISRA guidelines which state "... only 1 break per while loop". This has caused me to rewrite my if and while loops:

bool can_continue = true;

if (can_continue)
{
  status = Do_Something();
  if (status != SUCCESS)
  {
    can_continue = false;
  }
}

if (can_continue)
{
  status = Do_Another_Thing();
  can_continue = status == SUCCESS;
}

//.. and so on.

The idea is to set a flag to "false" if execution can't continue. Check it after any segment can cause execution to fail.

于 2013-03-13T23:34:25.443 に答える
-1
while( true ){

    if( condition == true ){
        goto bye;
    }
}

:bye

Just don't submit this on your homework...

于 2013-03-13T22:30:19.033 に答える
-1

Think it is as crazy as useless.

However, suppose you want 3 iterations, you'll define an array of bool of 3 elements (all set to true). On each iteration you set the current element to false, until you reach the end of your array.

于 2013-03-14T01:40:51.247 に答える