开发者

Did I do this program correctly?

开发者 https://www.devze.com 2023-03-20 16:51 出处:网络
Assignment is to Complete the 8 queens 2 dimensional array program with backtracking. #include <iostream>

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!).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号