简体   繁体   中英

Did I do this program correctly?

Assignment is to Complete the 8 queens 2 dimensional array program with backtracking.

#include <iostream>

using namespace std;

int main() {
    int b[8][8] = { 0 };
    int r, c, i;
    int count = 1;
    b[0][0] = 1;
    c = 0;

nextColumn:
    c++;
    if (c == 8)
        goto print;
    r =- 1;

nextRow:
    r++;
    if (r == 8)
        goto back;
    for (i = 0; i < c; i++) {
        if (b[r][i] == 1)
            goto nextRow;
    }
    for (i = 0; (r - i) >= 0 && (c - i) >= 0; i++) {
        if (b[r - i][c - i] == 1)
            goto nextRow;
    }
    for (i = 0; (r + i) < 8 && (c - i) >= 0; i++) {
        if (b[r + i][c - i] == 1)
            goto nextRow;
    }
    b[r][c] = 1;
    goto nextColumn;
    c--;
    if (c == -1)
        return 0;
    r = 0;
    while (b[r][c] != 1)
        r++;
    b[r][c] = 0;
    goto nextRow;
    cout << endl;
    cout << "Result No." << count << endl;
    cout << endl;
    for (r = 0; r < 8; r++){
        for (int c = 0; c < 8; c++){
            cout << b [r][c];
        }
        cout << endl;
    }
    count++;
    goto back;
}

Well, no.

  • Everything is one big function; it should be broken in to little functions
  • The program -- like all programs -- should be self-testing. There should be a function that returns true if the program worked and false if it didn't.
  • You're using single-character variable names; variables should have meaningful names.
  • You're writing to cout at every level; you should be performing calculations, returning results, then (optionally) printing results to cout.
  • You're using goto , which is generally ConsideredHarmful. And you're using it a lot , which is always ConsideredHarmful.

If you care about your program being correct, make sure it's readable first.

So properly indent the program, declare (and init) variables where you use them, and stop using the goto statement. There's break if you want to bail out early from a for loop. (Or better, write the loop code in a separate function and use early returns.).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM