Python implements the eight queens problem and the problems encountered (using depth-first bfs and breadth-first dfs)

I am not used to python for small homework in artificial intelligence courses, so I wrote it all afternoon, and I will share it here, among which dfs uses recursion.
If you use c++ or java, it should be faster. Using python encountered a lot of pitfalls

1. Code implementation

print("===============================================")




class Point:
    def __init__(self, x, y, board):
        self.x=x
        self.y=y
        self.board=board


def BFS(n):
    n=int(n)
    queue = []
    for i in range(n):
        board = initBoard(n)
        board[0][i]=1
        point = Point(0,i,board)
        queue.append(point)
    res = 0
    while(len(queue) != 0):
        point = queue.pop(0)
        row=point.x
        col=point.y

        if(row==n-1): #已经最后一行,直接输出
            res += 1
            print("---------------------------")
            print("第", res, "种结果如下:")
            print(point.board)
        else:
            for j in range(n):
                if(check(point.board, row + 1, j, n)):
                    #这个点可以加入到队列之中
                    board=copy.deepcopy(point.board)
                    board[row+1][j] = 1
                    temp = Point(row + 1, j, board)
                    queue.append(temp)
    print("当输入为", n, "时,共计", res, "种方式")
    return



def DFS(n):
    n=int(n)
    print("DFS")
    board = initBoard(n)
    print("打印初始化棋盘")


    print(board)
    print("---------------------------------------")



    for i in range(n):
        board[0][i]=1
        dp(n, 1, board)
        board[0][i]=0
    print("当输入为", n, "时,共计", cnt, "种方式")
    return

def dp(n, row, board): #print("调用dp函数")
    if(row == n):
        #能够完成
        global cnt
        cnt+=1
        print("第", cnt, "种结果如下:")
        print(board)
        print("-----------------------------------")
        return
    for j in range(n):
        if(check(board, row, j, n)):
            #print("成功",row, " " ,j)
            #修改棋盘
            board[row][j]=1
            row += 1
            dp(n, row, board)
            row -= 1
            board[row][j]=0
    return


def initBoard(n):
    #初始化全0的2维数组,1代表选择,0代表未被选
    board = np.zeros((n,n),dtype=int)
    return board

#检测新添加的棋子是否合法
def check(board, row, col, n): #向上寻找是否合规
    temp_x=row #行数
    temp_x-=1
    while(temp_x>=0):
        for j in range(n):
            if(board[temp_x][j]==1):
                # print("检测到1的位置",temp_x,",",j)
                # print("原始位置",row,",",col)
                if(j==col or abs(j-col)==abs(temp_x-row)):
                    return False
        temp_x-=1
    return True




while(True):
    choice = input("请选择BFS或者DFS实现(按0代表BFS,按1代表DFS,按q离开):")
    if (choice == '0'):
        n=input("请输入棋盘大小:")
        BFS(n)
    elif (choice == '1'):
        # global cnt
        cnt = 0
        n=input("请输入棋盘大小:")
        DFS(n)
    elif (choice == 'q'):
        break
    else:
        print("请重新输入!")

2. The pits encountered (mainly because they are not familiar with python syntax)

2.1 Assignment is a shallow copy

Encountered a bug, no matter how the assignment was made, the assignment was unsuccessful. Later, it was found that the problem was a shallow copy, and the subsequent use of deepcopy was successful.

2.2 The or operator is or

At first I thought it was the same as c++, using || to indicate that the result reported an error, changed to | and no error was reported, but the result of the program running was wrong. I searched for a long time to find the problem

2.3 Global variables

Python does not have pointers, and there is no way to use pointers to pass values ​​when writing recursion, so global variables are thought of, but global variables are not written outside like C++, you need to use the global keyword, and the use of the global keyword is also quite complicated, recorded here one time.

global g
g = 0
def p1():
    c = g+1
    print(c)
def p2():
    g+=1
    print(g)
p1()
p2()

The appeal code p1 can run, but p2 cannot run, the result is as follows. The reason is not clear, I hope someone can explain it,
insert image description here
but when we write recursion, we need to update this global variable, the correct way to use it

g = 0
def p1():
    c = g+1
    print(c)
def p2():
    global g
    g+=1
    print(g)
p1()
p2()

Put global into the method instead of defining it outside

Guess you like

Origin blog.csdn.net/qq_43471945/article/details/127855564