Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Create 0052-n-queens-ii.java#3441

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
felivalencia3 merged 1 commit intoneetcode-gh:mainfromTetsuya3850:patch-2
May 22, 2024
Merged
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletionsjava/0052-n-queens-ii.java
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
class Solution {
int count = 0;

public int totalNQueens(int n) {
Set<Integer> colSet = new HashSet<>();
Set<Integer> posDiagSet = new HashSet<>(); // (r + c)
Set<Integer> negDiagSet = new HashSet<>(); // (r - c)
backtrack(0, n, colSet, posDiagSet, negDiagSet);
return count;
}

private void backtrack(
int row,
int n,
Set<Integer> colSet,
Set<Integer> posDiagSet,
Set<Integer> negDiagSet) {
if (row == n) {
count += 1;
return;
}

for (int col = 0; col < n; col++) {
if (colSet.contains(col)
|| posDiagSet.contains(row + col)
|| negDiagSet.contains(row - col)) {
continue;
}
colSet.add(col);
posDiagSet.add(row + col);
negDiagSet.add(row - col);
backtrack(row + 1, n, colSet, posDiagSet, negDiagSet);
colSet.remove(col);
posDiagSet.remove(row + col);
negDiagSet.remove(row - col);
}
}
}

[8]ページ先頭

©2009-2025 Movatter.jp