-
Notifications
You must be signed in to change notification settings - Fork 0
add 4 files with queen problem solution and complexity.md with comments #1
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
Open
dfdf11-cpu
wants to merge
1
commit into
main
Choose a base branch
from
queens
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
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,26 @@ | ||
| анализ сложности решений задачи N ферзей. | ||
|
|
||
|
|
||
|
|
||
| переборное решение. | ||
|
|
||
| сложность: O(N! × N²), так как генерирует все перестановки N элементов: O(N!); | ||
| для каждой перестановки проверяет корректность: O(N²) операций; | ||
| и в худшем случае проверяет все N! расстановок. | ||
|
|
||
|
|
||
|
|
||
| рекурсивное решение. | ||
|
|
||
| сложность: O(N!) работает быстрее, чем полный перебор. | ||
| в худшем случае перебирает все возможные расстановки: O(N!); | ||
| но отсекает многие неподходящие ветви на ранних этапах, что ускоряет процесс работы. | ||
|
|
||
|
|
||
|
|
||
| быстрое решение. | ||
|
|
||
| сложность: O(N!). | ||
| использует битовые операции, что значительно ускоряет проверки: | ||
| 1)проверка столбцов и диагоналей: O(1); | ||
| 2)поиск доступных позиций: O(1) с битовыми операциями. |
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,24 @@ | ||
| def fast_n_queens(n): | ||
| def solve(row, columns, d1, d2): | ||
| if row == n: | ||
| return 1 | ||
|
|
||
| count = 0 | ||
| available = ((1 << n) - 1) & ~(columns | d1 | d2) | ||
|
|
||
| while available: | ||
| position = available & -available | ||
| available -= position | ||
|
|
||
| count += solve( | ||
| row + 1, columns | position, (d1 | position) << 1, (d2 | position) >> 1 | ||
| ) | ||
|
|
||
| return count | ||
|
|
||
| return solve(0, 0, 0, 0) | ||
|
|
||
|
|
||
| n = int(input("введите количество ферзей N: ")) | ||
| result = fast_n_queens(n) | ||
| print(f"количество корректных расстановок {n} ферзей: {result}") | ||
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 @@ | ||
| import itertools | ||
|
|
||
| def is_valid_board(board): | ||
| n = len(board) | ||
| for i in range(n): | ||
| for j in range(i + 1, n): | ||
| if abs(i - j) == abs(board[i] - board[j]): | ||
| return False | ||
| return True | ||
|
|
||
|
|
||
| def brute_force_n_queens(n): | ||
| count = 0 | ||
| for permutation in itertools.permutations(range(n)): | ||
| if is_valid_board(permutation): | ||
| count += 1 | ||
| return count | ||
|
|
||
|
|
||
| n = int(input("введите количество ферзей N от 1 до 10: ")) | ||
|
|
||
| if n < 1 or n > 10: | ||
| print(f"N={n} не подходит для переборного метода.") | ||
| else: | ||
| result = brute_force_n_queens(n) | ||
| print(f"количество корректных расстановок {n} ферзей: {result}") |
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,22 @@ | ||
| def recursive_n_queens(n): | ||
| def is_safe(board, row, col): | ||
| for i in range(row): | ||
| if board[i] == col or abs(board[i] - col) == abs(i - row): | ||
| return False | ||
| return True | ||
|
|
||
| def solve(row, board): | ||
| if row == n: | ||
| return 1 | ||
| count = 0 | ||
| for col in range(n): | ||
| if is_safe(board, row, col): | ||
| board[row] = col | ||
| count += solve(row + 1, board) | ||
| return count | ||
|
|
||
| return solve(0, [-1] * n) | ||
|
|
||
| n = int(input("введите количество ферзей N: ")) | ||
| result = recursive_n_queens(n) | ||
| print(f"количество корректных расстановок {n} ферзей: {result}") |
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.
Для такой сложной логики обязательно нужны комментарии с пояснениями