最近复习了一下算法,太久没有碰脑子都生锈了。python容易调先上python的代码,往后有时间再上Java的。
# -*- coding: utf-8 -*-
import copy;
__author__ = \'jinyao.xian\';
total = 0;
class Position:
def __init__(self, x, y):
self.x = x;
self.y = y;
def eight_queen(num):
blank_chess_board = [[0 for _ in range(num)] for _ in range(num)];
def queen(chess_board, nextx, chess_num=0):
if chess_num == num: # 可使用nextx作为递归最终条件 nextx == num
print_board(chess_board);
else:
for y in range(len(chess_board[nextx])): # 纵向遍历
if can_use_this_position(Position(nextx, y), chess_board):
new_chess_board = copy.deepcopy(chess_board);
put_chess(Position(nextx, y), new_chess_board);
queen(new_chess_board, nextx + 1, chess_num+1); # 横向遍历
queen(blank_chess_board, 0);
def print_board(chess_board):
global total;
total += 1;
for x in chess_board:
print(x);
print(\"\")
def can_use_this_position(position, chess_board):
if 1 in chess_board[position.x]:
return False;
for x in range(len(chess_board)):
if 1 == chess_board[x][position.y]:
return False;
tmp = abs(x - position.x);
if position.y - tmp >= 0 and chess_board[x][position.y - tmp] == 1:
return False;
elif position.y + tmp < len(chess_board[x]) and chess_board[x][position.y + tmp] == 1:
return False;
return True;
def put_chess(position, chess_board):
chess_board[position.x][position.y] = 1;
return chess_board;
if __name__ == \'__main__\':
eight_queen(8);
print(total);
| y7 | ||||||||
| y6 | ||||||||
| y5 | ||||||||
| y4 | ||||||||
| y3 | ||||||||
| y2 | ||||||||
| y1 | ||||||||
| y0 | ||||||||
| x0 | x1 | x2 | x3 | x4 | x5 | x6 | x7 |
上表格为我的思路
主要遇到的问题:
棋盘没有副本,所以用了个深度拷贝来维持剩下棋子所对应的棋盘
继续阅读与本文标签相同的文章
下一篇 :
学习Kafka,先从这四个基础概念入手
-
Apache Flink 进阶(一):Runtime 核心机制剖析
2026-05-18栏目: 教程
-
RocketMQ一个新的消费组初次启动时从何处开始消费呢?
2026-05-18栏目: 教程
-
Spring Boot2中整合atomikos来实现不同类型数据库的分布式事务一致性
2026-05-18栏目: 教程
-
Git 如何针对项目修改本地提交提交人的信息
2026-05-18栏目: 教程
-
工作几年只会增删改查怎么了,大神们都是从第一行代码开始的
2026-05-18栏目: 教程
