1

嘿,我无法让我的代码比较给定行或列的整数并阻止以确保这些参数中没有重复项。我不知道用 3 种不同的方法分离这三个约束是否是一个好主意,或者只是尝试一次做所有事情。

public static rowCheck(int[][] nsudokuBoard) {

    for (int i =0; i < 9; i++) {

        for (int j = 0; j < 9; j++) { 
            // (nsudokuBoard)
        }
    }
}

这是我开始的代码。在你们抨击我什至无法编译这个之前,我坚持如何比较二维数组的一行的所有值。

4

3 回答 3

2

您可以比较二维数组的所有值,如下面的代码所示:

void validate(final int[][] nsudokuBoard) {
    final int width = nsudokuBoard[0].length;
    final int depth = nsudokuBoard.length;

    for (int i = 0; i < width; i++) {
        int j = i;
        int reference = nsudokuBoard[i][j];

        do {
            if (j < width) {
                int current = nsudokuBoard[i][j];

                if (current == reference) {
                // invalid entry found do something
                }
            }
            if (j < depth) {
                // note reversed indexes
                int current = nsudokuBoard[j][i];

                if (current == reference) {
                // invalid entry found do something
                }
            }
            ++j;
        } while ((j >= width) || (j >= depth));
    }
}

我没有尝试编译此代码,但它应该让您了解如何完成任务。我建议不要传入,而是int[][] sudokuBoard应该定义一个封装 aSudokuSquare和传入概念的类SudokuSquare[][],这样你的validate方法可以返回List<SudokuSquare>包含所有违规条目的 a。

于 2012-02-16T12:59:49.670 回答
0

我将展示你如何做一排,然后你可以找出其余的。我假设您的价值观是包容19的,并且您没有任何零或任何“未填充的条目”。

boolean isRowValid(int[][] grid, int row) {
  boolean[] seen = new boolean[9];
  int row; // chosen somewhere else
  for (int col = 0; col < 9; col++) {
    if (seen[grid[row][col] - 1]) { // if we've seen this value before in this row
      return false; // there is a duplicate, and this is a bad sudoku
    }
    seen[grid[row][col] - 1] = true; // mark us as having seen this element
  }
  return true; // we're all good
}
return true; // this row is fine
于 2012-02-16T11:33:28.280 回答
0

创建一个包含字段 row、col、block、value 的类 Cell;然后用字段单元格=单元格[]创建一个类矩阵,填充矩阵。使用主要方法 Matrix matrix = init(int[][]) 和 check(matrix) 制作一个类检查器,其中 init(·) 填充矩阵。boolean ok = check(matrix) where check(Matrix) if(!rowcheck())return false; if(!colcheck()) 返回 false 等;

创建一些方法,如 getrows()、getrow(r) 和 for(Cell cell: matrix.values()) 来过滤掉你想要的。

有点乏味,但我已经做到了,它坚如磐石。

请注意,对矩阵进行过滤可能看起来很愚蠢,但计算机速度很快,问题是 O(1),因为它是 9x9。

于 2015-05-31T15:02:44.370 回答