毛头小子


私信TA

用户名:uq_10571446592

访问量:486

签 名:

救赎未来的自己!

等  级
排  名 26462
经  验 528
参赛次数 0
文章发表 8
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

解题思路:

深度递归

注意事项:

如果完成了75%并出现运行错误,可能是因为数组越界

参考代码:

m, n = map(int, input().strip().split())

figure = []#存储输入的数组

temp = [[0] * m for i in range(n)]#标记每个位置的数是否被访问过

ans = []#存储成功分割后每个组合中含有的数字个数

while len(figure) < n:

    try:

        arr = list(map(int,input().strip().split()))

        figure.append(arr)

    except:

        break

allnum = 0

for i in range(n):

    allnum += sum(figure[i])

def dfs(a, x, y):

    global figure

    global temp

    global allnum

    global ans

    temp[x][y] = 1

    if a == allnum:

        b = 0

        for i in range(len(figure)):

            b += sum(temp[i])

        ans.append(b)

        return

    for k, j in [x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1]:

        if 0<=k<len(temp) and 0<=j<len(temp[0]) and not temp[k][j] and a + figure[k][j] <= allnum:#可能会出现数组越界的地方,注意分别对应数组的行数和列数是多少

            dfs(a + figure[k][j], k, j)

            temp[k][j] = 0

    return

if allnum % 2:

    print(0)

else:

    allnum //= 2

    dfs(figure[0][0], 0, 0)

    if ans:#虽然所有的数字可以被分为和相同的两部分,但不一定可以形成通路,即无法成功连接

        print(min(ans))

    else:

        print(0)


 

0.0分

0 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区