-
Notifications
You must be signed in to change notification settings - Fork 0
Added N-Queens Problem #10
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| def n_queens_fast(n): | ||
| """Оптимизированное решение с использованием битовых операций""" | ||
|
|
||
| def solve(row, cols, diag1, diag2): | ||
| nonlocal count | ||
| if row == n: | ||
| count += 1 | ||
| return | ||
|
|
||
| available = ((1 << n) - 1) & ~(cols | diag1 | diag2) | ||
|
|
||
| while available: | ||
| pos = available & -available | ||
| available -= pos | ||
|
|
||
| solve(row + 1, cols | pos, (diag1 | pos) << 1, (diag2 | pos) >> 1) | ||
|
|
||
| count = 0 | ||
| solve(0, 0, 0, 0) | ||
| return count | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| Оценка сложности решений | ||
| 1. Переборное решение | ||
| Сложность: O(N! × N²) | ||
|
|
||
| Обоснование: | ||
| Генерируются все перестановки N элементов: N! вариантов. | ||
| Для каждой перестановки проверяется корректность за O(N²) в худшем случае. | ||
| Фактическое время работы растет факториально, что делает решение непригодным для N > 10. | ||
|
|
||
| 2. Рекурсивное решение (backtracking) | ||
| Сложность: O(N!) в худшем случае, но на практике меньше | ||
|
|
||
| Обоснование: | ||
| Алгоритм использует возврат (backtracking), отсекая заведомо неверные расстановки. | ||
| В худшем случае перебирается N! вариантов. | ||
| Благодаря отсечениям (проверка столбцов и диагоналей за O(1)) работает значительно быстрее переборного решения. | ||
|
|
||
| 3. Оптимизированное решение (битовые операции) | ||
| Сложность: O(N!), но с существенно меньшей константой | ||
|
|
||
| Обоснование: | ||
| Использует битовые операции для максимально быстрой проверки доступных позиций. | ||
| Все операции (проверка и установка позиций) выполняются за O(1). | ||
| Константа времени выполнения в 10-100 раз меньше, чем у обычного backtracking. | ||
|
|
||
| Итоги: | ||
| Все решения имеют факториальную сложность в худшем случае | ||
| Для N > 16 требуется принципиально иной подход или эвристические алгоритмы | ||
| Оптимизированное решение наиболее эффективно благодаря минимальным накладным расходам |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| import itertools | ||
|
|
||
|
|
||
| def is_valid(board): | ||
| """Проверяет, является ли расстановка корректной""" | ||
| n = len(board) | ||
| for i in range(n): | ||
| for j in range(i + 1, n): | ||
| if board[i] == board[j]: | ||
| return False | ||
|
|
||
| if abs(board[i] - board[j]) == abs(i - j): | ||
| return False | ||
| return True | ||
|
|
||
|
|
||
| def n_queens_bruteforce(n): | ||
| """Перебор всех возможных расстановок""" | ||
| if n < 1 or n > 10: | ||
| return 0 | ||
|
|
||
| count = 0 | ||
|
|
||
| for permutation in itertools.permutations(range(n)): | ||
| if is_valid(permutation): | ||
| count += 1 | ||
| return count |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| def n_queens_recursive(n): | ||
| """Рекурсивное решение с возвратом""" | ||
|
|
||
| def backtrack(row, cols, diag1, diag2): | ||
| nonlocal count | ||
| if row == n: | ||
| count += 1 | ||
| return | ||
|
|
||
| for col in range(n): | ||
| if cols[col] or diag1[row + col] or diag2[row - col + n - 1]: | ||
| continue | ||
|
|
||
| cols[col] = diag1[row + col] = diag2[row - col + n - 1] = True | ||
| backtrack(row + 1, cols, diag1, diag2) | ||
|
|
||
| cols[col] = diag1[row + col] = diag2[row - col + n - 1] = False | ||
|
|
||
| count = 0 | ||
|
|
||
| cols = [False] * n | ||
| diag1 = [False] * (2 * n - 1) | ||
| diag2 = [False] * (2 * n - 1) | ||
|
|
||
| backtrack(0, cols, diag1, diag2) | ||
| return count |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Хотелось бы видеть комментарии, поясняющие эту сложную логику.
Битовые операции достаточно тяжело воспринимать вот так, остается только догадываться или вручную вычислять что же делает каждая из них.