The 11th National Games python test E: toy snake

Toy snake


[Problem description]
Xiaolan has a toy snake with a total of 16 sections, marked with numbers 1 to 16. Each section is in the shape of a square. Two adjacent sections can be in a straight line or at an angle of 90 degrees.
Xiaolan also has a 4 × 4 square box for storing toy snakes. The squares of the box are marked with a total of 16 letters from A to P. Xiao Lan can fold her toy snake into the box. He found that there are many ways to put toy snakes in.
The following figure shows two solutions:
Please help Xiaolan calculate how many different solutions there are in total. If in the two schemes, a certain section of the toy snake is placed in a different grid of the box, it is considered to be a different scheme.
Insert picture description here
Idea:
The meaning of this question is how to complete 15 steps from 0, 0 when the starting point is 0, 0, and then find out how many possibilities there are. When we find the possibility of 0, 0, we will traverse all the possibilities. At the starting point, just add the number of steps. We use the dfs method to find the starting point 0, so it is possible to traverse one side and then traverse the starting point to find it.
Answer: 552
program:

nu=0
f=[[0,1],[1,0],[-1,0],[0,-1]]
def dfs(m,x,y):
    global nu
    if m==15:
        nu+=1
        return
    for i in f:
        if -1<x+i[0]<4 and -1<y+i[1]<4 and d[x+i[0]][y+i[1]]==0:
            d[x][y]=1
            dfs(m+1,x+i[0],y+i[1])
            d[x][y]=0
    
for i in range(4):
    for i1 in range(4):
        d=[[0 for i1 in range(4)]for i in range(4)]
        dfs(0,i,i1)
print(nu)

Reprinting is prohibited. Only for self-study. No responsibility for program errors.

Guess you like

Origin blog.csdn.net/weixin_46640345/article/details/112755656
Recommended