leetcode 36. Valid Sudoku (medium)

版权声明:by ruohua3kou https://blog.csdn.net/ruohua3kou/article/details/89058665

实现题,注意细节和边界

class Solution
{
  private:
	bool checkid(char c, bool used[])
	{
		if (c == '.')
			return true;
		if (used[c - '1'])
			return false;
		return used[c - '1'] = true;
	}

  public:
	bool isValidSudoku(vector<vector<char>> &board)
	{
		bool used[9];
		// 检查行列
		for (int i = 0; i < 9; i++)
		{
			// 检查行.
			fill(used, used + 9, false);
			for (int j = 0; j < 9; j++)
			{
				if (!checkid(board[i][j], used))
					return false;
			}

			// 检查列.
			fill(used, used + 9, false);
			for (int j = 0; j < 9; j++)
			{
				if (!checkid(board[j][i], used))
					return false;
			}
		}

		// 检查格子
		for (int r = 0; r < 3; r++)
		{
			for (int c = 0; c < 3; c++)
			{
				fill(used, used + 9, false);
				for (int i = r * 3; i < r * 3 + 3; i++)
				{
					for (int j = c * 3; j < c * 3 + 3; j++)
					{
						if (!checkid(board[i][j], used))
							return false;
					}
				}
			}
		}
		return true;
	}
};

猜你喜欢

转载自blog.csdn.net/ruohua3kou/article/details/89058665