C 递归以在网格的行和列中检测重复

C++ Recursion to detect duplicates in row and column of grid

本文关键字:检测 递归 网格      更新时间:2023-10-16

我正在编码递归算法以获取用户输入n并制作n x n网格,其中相同的数字在一行或列上都不会出现两次。几乎所有内容都在起作用,并且重复的列没有出现在列中,但是我难以使行工作起作用。

我用于在行中检查重复项的代码是函数orowduplicates。复制品仍在出现,偶尔会丢掉细分错误,但我不确定为什么。

事先感谢您的帮助!

// Author: Eric Benjamin
// This problem was solved using recursion. fill() is the recursive function.

#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
void fillOptions();
void fill(int arrayPosition);
int inputNum;
int gridSize;
int *grid;
int allOptionsSize = 0;
int *allOptions;
int main() {
    cout << "Please enter a number!" << endl;
    cin >> inputNum;
    gridSize = inputNum * inputNum;
    grid = new int[gridSize];
    allOptions = new int[inputNum];
    for (int i = 0; i < inputNum; i++) {
         allOptions[i] = i + 1;
         allOptionsSize++;
    }
    srand((unsigned)time(0));
    fill(0);
    delete[] grid;
    delete[] allOptions;
    return 0;
}
bool noColumnDuplicates(int arrPosition, int valueToCheck) {
    for (int i = 1; i < inputNum; i++) {
        if (arrPosition - (inputNum * i) >= 0) {
            if (grid[arrPosition - (inputNum * i)] == valueToCheck) {
                return false;
            }
        }
    }
    return true;
}
bool noRowDuplicates(int arrPosition, int valueToCheck) {
    int rowPosition = arrPosition % inputNum; // 0 to num - 1
    if (rowPosition > 0) {
        for (int p = 1; p < rowPosition; p++) {
            if (grid[arrPosition - p] == valueToCheck) {
                return false;
            }
        }
    }
    return true;
}
void fill(int arrayPosition) {
    if (arrayPosition < gridSize) {
        int randomPosition = rand() % allOptionsSize;
        grid[arrayPosition] = allOptions[randomPosition];
        if (noColumnDuplicates(arrayPosition, grid[arrayPosition])) {
            if (noRowDuplicates(arrayPosition, grid[arrayPosition])) {
                if (arrayPosition % inputNum == 0) {
                    cout << endl;
                }
                cout << grid[arrayPosition] << " ";
                fill(arrayPosition + 1);
            } else {
                fill (arrayPosition);
            }
        } else {
            fill(arrayPosition);
        }
    }
}

noRowDuplicates从不测试一行的第一个元素,当您试图填充一排的第一个元素时,这是有道理的,但没有其他时间。