我有一个问题,我必须为给定的 4x4 数独编写自动解决方案,这意味着数字只能达到 1 2 3 4。这是数独的简化版本,因为我还是编程新手。
我有一个给定的模板,其中生成了随机数独,我必须编写一个代码来自动解决数独问题。
这是我一开始必须解决的数独问题
sudoku[6] = [[" ","2"," "," "],
[" "," ","2"," "],
[" "," "," ","3"],
["4"," "," "," "]
我的想法是将“1234”插入空的“”中,然后当列、行和象限中已经存在一个数字时,从“1234”中删除这些数字。所以我想做的是使用循环遍历表中的所有位置,当我发现例如“1”时,我将从“1234”中删除1。
这是我的代码的开始,它似乎在我到达 if 的那一刻不起作用,你们能告诉我我做错了什么或者为什么当我到达我的 If 时它不起作用。先感谢您。
var sudoku = sudoku[6];
// function to put "1234" into empty space ""
var concatenate = function (s)
{
for (i=0; i<s.length; i++)
for (j=0; j<s.length; j++)
if (sudoku[i][j] === " ")
sudoku[i][j] = "1234";
};
concatenate(sudoku);
// function to solve the sudoku automatically.
var solve = function (t)
{
for (i = 0; i<t.length; i++)
for (j=0; j<t.length; j++)
for (k=j; k<(4+j); k++)
if (sudoku[i][j].length === 1) // this is where it seems to bug, in this if im trying to find the position where we only have one number and not "1234"
var s = sudoku[i][j];
if (sudoku[i][k-j] !== ("1" || "2" || "3" || "4")) // here im finding the position of all position in the sudoku where ive got "1234" so i can remove the number found in the previous if.
{
var index = sudoku[i][k-j].indexOf(s);
var string_new = sudoku[i][k-j].substring(0,index) + sudoku[i][k-j].substring(index+1, 4);
sudoku[i][k-j] = string_new;
}
};