Created
April 10, 2020 05:41
-
-
Save bitristan/6a7224ec8ac1a19ff6bc00a88171df17 to your computer and use it in GitHub Desktop.
八皇后问题
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
N = 8 | |
def isVaild(path, dcolumn): | |
drow = len(path) | |
for row, column in enumerate(path): | |
if column + drow - row == dcolumn: | |
return False | |
if column - (drow - row) == dcolumn: | |
return False | |
return True | |
def backtrace(path, choice): | |
if (len(path) == N): | |
print(path) | |
else: | |
for c in list(choice): | |
# 去掉isValid这个条件,就变成了一个全排列算法 | |
if (not isVaild(path, c)): | |
continue | |
path.append(c) | |
choice.remove(c) | |
backtrace(path, choice) | |
path.remove(c) | |
choice.append(c) | |
def main(): | |
path = [] | |
choice = [i for i in range(N)] | |
backtrace(path, choice) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment