10th national competition java test question 5: statistics

Statistics


6*6 picture, start from the upper left corner, do not take the repeated path and walk back to the upper left corner point within 12 steps, ask the number of plans

The idea
here is that the recursion starts from 0, 0, and within 12 steps, we return to the original place without repeating. We can directly use dfs to start deep recursion from 0, 0 to count all the statistics within 12 steps and then watch. See how many times you have returned to the origin within 12 steps. Because ((0,0),(0,1),(0,0)) and ((0,0),(1,0),(0,0)) this has gone the repeated path. All the final answers are Subtract 2.
if -1<x1<6 and -1<y1<6 and d[x1][y1]==0: This means that you can go to the next step, d[x1][y1]==0 means He has never taken this jump. After the conditions are met, d[x1][y1]==1 marks him as he has passed, and then enters dfs. When the function ends, d[x1][y1]==0 needs to be traced back.
Result: 208-2=206

program:

f=[[1,0],[-1,0],[0,1],[0,-1]]
d=[[0 for i in range(6)] for i in range(6)]
nu=0
def dfs(x,y,m):
    global nu
    
    if x==0 and y==0 and 1<=m<=12:
        nu+=1
        return
    if m> 12:
        return
    for i in f:
        x1=x+i[0]
        y1=y+i[1]
        if -1<x1<6 and -1<y1<6  and d[x1][y1]==0:
            d[x1][y1]=1
            dfs(x1,y1,m+1)
            d[x1][y1]=0
    


dfs(0,0,0)
print(nu-2)

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

Guess you like

Origin blog.csdn.net/weixin_46640345/article/details/112782364