Algorithm Design and Analysis Experiment 5 - Traveling Salesman Problem | Experiment 6 - n Queens Problem

Directions -> Traveling Salesman Problem

1 question

n queen problem

2 problem analysis

The n n chessboard can be regarded as a n n table, and the queen Q must be placed, and two conditions need to be met.
Condition 1: two or more queens cannot be placed in the same column.
Condition 2: Queens cannot exist on the slash

3 Problem Modeling

i, j represent row values, a[i], a [j] represent column values
​​|a[i]-a[j]| != |ij | 0<i<len (the number of queens) i+1<j<len (the number of queens) function logic is implemented through two layers of for loops, by defining constants and incrementing in the statement block, it is judged whether the statement block is Execute to filter the solution space







4 Algorithm source code

per_result = []
def per(lst,s,e):
    if s == e:
        per_result.append(list(lst))
    else:
        for i in range(s,e):
            lst[i],lst[s] = lst[s],lst[i]#试探
            per(lst,s+1,e)#递归
            lst[i],lst[s] = lst[s],lst[i]#回溯
#剪枝函数
#args:[1,2,3,4]
#return true or false
def shear(lst):
    result = 0
    for i in range(len(lst)):
        for j in range(i+1,len(lst)):
            if(abs(lst[j] - lst[i]) == abs(j-i)):
                result += 1
    if(result > 0):
        return True
    else:
        return False
#格式打印函数
def stamp(st):
    for i in st:
        for j in range(len(i)):
            a = ("."*(i[j]-1)+"#"+"."*(len(i)-i[j]))
            # print(a,"\t","第{}个皇后放在棋盘的第{}列".format(j+1,i[j]))
            print(a, "\t", "({},{})".format(j + 1, i[j]))
        print(" ")#负责空行
num = eval(input("请输入皇后的个数:"))
lst = [i+1 for i in range(num)]
per(lst,0,num)
queen_lst = []
for i in per_result:
    if(shear(i) == False):
        queen_lst.append(i)
stamp(queen_lst)
print("共{:d}种可能".format(len(queen_lst)))

5 test data

4

6 program running results

insert image description here
For more university coursework experiment training, please pay attention to the official account: Timewood
Reply to related
keywords

Guess you like

Origin blog.csdn.net/qq_43374681/article/details/122382107