LoginSignup
0
0

More than 1 year has passed since last update.

36 解答

Posted at

参考

Nick White : LeetCode 36. Valid Sudoku (Algorithm Explained)
GeeksforGeeks : HashSet add() Method in Java
英語がわかる人は絶対こっちのほうがわかりやすいので、[Nick White]さんのYouTubeを見てね! (ステマではないです)

解答

	public boolean isValidSudoku(char[][] board) {
		Set<String> seen = new HashSet<>();
		for (int i = 0; i < 9; i++) {
			for (int j = 0; j < 9; j++) {
				char current_val = board[i][j];
				if (current_val != '.') {// if each mass contains value
					if (!seen.add(current_val + " found in row " + i)
							|| !seen.add(current_val + " found in column " + j)
							|| !seen.add(current_val + " found in sub box " + i / 3 + "-" + j / 3)) {// if the element
																										// is already
																										// contaitned in
																										// the HashSet
						return false;
					}

				}

			}
		}
		return true;

	}

簡単な解説

解答としては HashSet を3つ作ってそれぞれ確認する方法もあるが、今回はHashSetだけを使っている。
add() メソッドはHashSetに要素を追加する機能もあるが、boolean を返す機能もある。

HashSet add() Method

GeeksforGeeks : HashSet add() Method in Java
ここに書いてある通り、
HashSetに要素がすでにある場合は -> False
HashSetに要素がない場合は -> True

つまり、もっと簡単に言うと
その要素がuniqueではない場合は -> false
その要素がuniqueな場合は -> True

と認識しているがあっているかは自信がない。

どちらが先に実行されるか問題

if (!seen.add(current_val + " found in row " + i)
							|| !seen.add(current_val + " found in column " + j)
							|| !seen.add(current_val + " found in sub box " + i / 3 + "-" + j / 3))

add() されてから評価しては常にfalseが帰ってきてしまうので、実際は,,,
評価(True or false)をしてからadd()する。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0