【LeetCode】C# 36、Valid Sudoku

来源:互联网 发布:软件结项文档 编辑:程序博客网 时间:2024/05/19 22:46

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character ‘.’.

这里写图片描述
A partially filled sudoku which is valid.

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

Sudoku数字游戏。

思路:利用HashSet确保每行每列每大格中的数字不重复。
行:if (board[i, j] != '.' && !rows.Add(board[i, j]))
列:if (board[j, i] != '.' && !columns.Add(board[j, i]))
小九宫格:
int RowIndex = 3 * (i / 3);
int ColIndex = 3 * (i % 3);
if (board[RowIndex + j / 3, ColIndex + j % 3] != '.' && !cube.Add(board[RowIndex + j / 3, ColIndex + j % 3]))

public class Solution {    public bool IsValidSudoku(char[,] board) {    for (int i = 0; i < 9; i++)        {            HashSet<char> rows = new HashSet<char>();            HashSet<char> columns = new HashSet<char>();            HashSet<char> cube = new HashSet<char>();            for (int j = 0; j < 9; j++)            {                if (board[i, j] != '.' && !rows.Add(board[i, j]))                    return false;                if (board[j, i] != '.' && !columns.Add(board[j, i]))                    return false;                int RowIndex = 3 * (i / 3);                int ColIndex = 3 * (i % 3);                if (board[RowIndex + j / 3, ColIndex + j % 3] != '.' && !cube.Add(board[RowIndex + j / 3, ColIndex + j % 3]))                    return false;            }        }        return true;    }}
原创粉丝点击