我对sudoku.I有问题,我必须检查是否有效,我被困在支票线和行,我不知道怎么做。
这是我的密码。
static int[] ReadValues()
{
string[] line = Console.ReadLine().Split(' ');
int[] array = Array.ConvertAll(line, int.Parse);
return array;
}
static int[,] CreateMatrix()
{
const int matrixSize = 9;
int[,] sudoku= new int[matrixSize, matrixSize];
for (int i = 0; i < matrixSize; i++)
{
int[] array = ReadValues();
for (int j = 0; j < matrixSize; j++)
{
sudoku[i, j] = array[j];
}
}
return sudoku;
}
static bool CheckLine(int[,] sudoku)
{
// this is the method where I'm stuck
}
static bool CheckRow(int[,] sudoku)
{
// this is the method where I'm stuck
}发布于 2022-08-07 10:45:27
这是我的代码战争任务的解决方案,但只有9x9
public class Sudoku
{
public static bool ValidateSolution(int[][] board)
{
for (int i = 0; i < 9; i++)
{
var line = GetLine(board, i, 9).Distinct();
var column = GetColumn(board, i, 9).Distinct();
if (line.Count() != 9 || column.Count() != 9)
return false;
}
for (int i = 0; i <= 6; i += 3)
{
var block = Get3x3Block(board, i, i).Distinct();
if (block.Count() != 9)
return false;
}
return true;
}
private static int[] GetLine(int[][] arr, int index, int count)
{
return arr[index].Take(count).ToArray();
}
private static int[] GetColumn(int[][] arr, int index, int count)
{
int[] result = new int[count];
for (int i = 0; i < count; i++)
result[i] = arr[i][index];
return result;
}
private static int[] Get3x3Block(int[][] arr, int index, int indentLeft)
{
var firstLine = GetLine(arr, index, 9).Skip(indentLeft).Take(3);
var secondLine = GetLine(arr, index + 1, 9).Skip(indentLeft).Take(3);
var thirdLine = GetLine(arr, index + 2, 9).Skip(indentLeft).Take(3);
return firstLine.Concat(secondLine).Concat(thirdLine).ToArray();
}
}发布于 2022-03-13 11:14:37
要检查某个行/列/框,您需要一个函数,该函数接受要查看的行/列/框,然后是要检查的数字。例如,检查列(假设9x9 sudoku)
bool checkColumn(int n_col, int n)
{
for (int row = 0; row < 9; row++)
{
if (n == sudokuMatrix[row][n_col])
return true;
}
return false; // col doesnt have number
}假设您正在编写sudoku解算器,则需要使用链接这里的回溯算法。
https://stackoverflow.com/questions/71456017
复制相似问题