Ejemplo n.º 1
0
        public bool ValidSudokuBox()
        {
            bool IsValid = true;

            elemList.ForEach(elem =>
            {
                if (IsValid == false)
                {
                    return;
                }

                sudokuelem elemRow = elemList.Find(x => x.x == elem.x && x.y != elem.y && elem.value == x.value && x.value != 0);
                sudokuelem elemCol = elemList.Find(x => x.y == elem.y && x.x != elem.x && elem.value == x.value && x.value != 0);
                sudokuelem elemBox =
                    elemList.Find(x =>
                                  (x.x != elem.x && x.y != elem.y) &&
                                  (x.x / 3 == elem.x / 3 && x.y / 3 == elem.y / 3) &&
                                  (x.value == elem.value && x.value != 0));

                if (elemCol != null || elemRow != null || elemBox != null)
                {
                    IsValid = false;
                    return;
                }
            });
            return(IsValid);
        }
Ejemplo n.º 2
0
        public bool SolveSudoku()
        {
            sudokuelem nextElem     = elemList.Find(x => x.value == 0);
            List <int> tempElemList = new List <int>()
            {
                1, 2, 3, 4, 5, 6, 7, 8, 9
            };
            bool IsSolved = false;

            if (!ValidSudokuBox())
            {
                return(false);
            }

            // All filed up
            if (nextElem == null)
            {
                return(true);
            }

            elemList.ForEach(x =>
            {
                if ((x.value != 0) && (x.x == nextElem.x || x.y == nextElem.y ||
                                       (x.x / 3 == nextElem.x / 3 && x.y / 3 == nextElem.y / 3)))
                {
                    tempElemList.Remove(x.value);
                }
            });

            tempElemList.ForEach(elem =>
            {
                if (IsSolved == false)
                {
                    nextElem.value = elem;
                    IsSolved       = SolveSudoku();
                    if (IsSolved == false)
                    {
                        nextElem.value = 0;
                    }
                }
            });

            nextElem = elemList.Find(x => x.value == 0);

            // All filed up
            if (nextElem == null)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }