Sudoku algorithm in C#

前端 未结 9 1121
南方客
南方客 2021-02-03 15:24

I need one liner (or close to it) that verifies that given array of 9 elements doesn\'t contain repeating numbers 1,2,3,...,9. Repeating zeroes do not count (they represent empt

9条回答
  •  长发绾君心
    2021-02-03 15:54

    This is an old question, but I recently was pointed to a 1 line solution using Oracle's custom SQL for doing tree-like structures. I thought it would be nice to convert this into Linq.

    You can read more on my blog about how to Solve Sudoku in 1 line of Linq

    Here is the code:

    public static string SolveStrings(string Board)
    {
        string[] leafNodesOfMoves = new string[] { Board };
        while ((leafNodesOfMoves.Length > 0) && (leafNodesOfMoves[0].IndexOf(' ') != -1))
        {
            leafNodesOfMoves = (
                from partialSolution in leafNodesOfMoves
                let index = partialSolution.IndexOf(' ')
                let column = index % 9
                let groupOf3 = index - (index % 27) + column - (index % 3)
                from searchLetter in "123456789"
                let InvalidPositions =
                from spaceToCheck in Enumerable.Range(0, 9)
                let IsInRow = partialSolution[index - column + spaceToCheck] == searchLetter
                let IsInColumn = partialSolution[column + (spaceToCheck * 9)] == searchLetter
                let IsInGroupBoxOf3x3 = partialSolution[groupOf3 + (spaceToCheck % 3) +
                    (int)Math.Floor(spaceToCheck / 3f) * 9] == searchLetter
                where IsInRow || IsInColumn || IsInGroupBoxOf3x3
                select spaceToCheck
                where InvalidPositions.Count() == 0
                select partialSolution.Substring(0, index) + searchLetter + partialSolution.Substring(index + 1)
                    ).ToArray();
        }
        return (leafNodesOfMoves.Length == 0)
            ? "No solution"
            : leafNodesOfMoves[0];
    }
    

提交回复
热议问题