Skip to content

Instantly share code, notes, and snippets.

@bitristan
Created April 10, 2020 05:41
Show Gist options
  • Save bitristan/6a7224ec8ac1a19ff6bc00a88171df17 to your computer and use it in GitHub Desktop.
Save bitristan/6a7224ec8ac1a19ff6bc00a88171df17 to your computer and use it in GitHub Desktop.
八皇后问题
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