/// <summary> /// checks whether removal of the cell is possible move /// </summary> /// <param name="cellToRemove"></param> /// <returns>Was the removal successful?</returns> private bool IsPossibleToRemoveValue(SudokuCell cellToRemove) { int row = Board.GetRow(cellToRemove); int column = Board.GetColumn(cellToRemove); int value = int.Parse(Board[row, column].Value); if (!ValueCanBeElsewhere(cellToRemove) || CanCellContainAnotherValue(row, column, value)) { return(true); } return(false); }
/// <summary> /// check if value of <paramref name="cellWithValue"/> can be elsewhere in the board /// </summary> /// <param name="cellWithValue"></param> /// <returns></returns> private bool ValueCanBeElsewhere(SudokuCell cellWithValue) { if (cellWithValue.IsEmpty()) { throw new ArgumentException($"Argument is not valid: {nameof(cellWithValue)} is an empty cell"); } int row = Board.GetRow(cellWithValue); int column = Board.GetColumn(cellWithValue); int value = int.Parse(Board[row, column].Value); var emptyRowValues = Board.GetNthRow(row).GetEmptyCells(); var emptyColumnValues = Board.GetNthColumn(column).GetEmptyCells(); var emptySquareValues = Board.GetSquareFromPosition(row, column).GetAllCells().GetEmptyCells(); var allValues = new List <List <SudokuCell> >() { emptyRowValues, emptyColumnValues, emptySquareValues }; // try to place value into other cells in the row, column and square foreach (var selectedValues in allValues) { bool isOnlyPlaceForValue = true; foreach (SudokuCell selectedCell in selectedValues) { cellWithValue.ClearValue(); selectedCell.Value = value.ToString(); var cellsRow = Board.GetNthRow(Board.GetRow(selectedCell)); var cellsCol = Board.GetNthColumn(Board.GetColumn(selectedCell)); var cellsSquare = Board.GetSquareFromPosition(Board.GetRow(selectedCell), Board.GetColumn(selectedCell)).GetAllCells(); if (cellsRow.IsSudokuValid() && cellsCol.IsSudokuValid() && cellsSquare.IsSudokuValid()) { isOnlyPlaceForValue = false; } selectedCell.ClearValue(); cellWithValue.Value = value.ToString(); cellWithValue.IsDefaultValue = true; } if (isOnlyPlaceForValue) { return(false); } } return(true); }
public static bool IsValid(this Board board) { return(!board.Squares.Any(square => !square.IsValid()) && !Enumerable.Range(1, board.Size).Any(row => !board.GetRow(row).IsValid()) && !Enumerable.Range(1, board.Size).Any(column => !board.GetColumn(column).IsValid())); }