蓝桥杯-剪格子-dfs-递归-python题解

剪格子

如下图所示,3 x 3 的格子中填写了一些整数。
±-–±-+
|10
1|52|
±-***–+
|20|30
1|
*******–+
| 1| 2| 3|
±-±-±-+
我们沿着图中的星号线剪开,得到两个部分,每个部分的数字和都是60。
本题的要求就是请你编程判定:对给定的m x n 的格子中的整数,是否可以分割为两个部分,使得这两个区域的数字和相等。
如果存在多种解答,请输出包含左上角格子的那个区域包含的格子的最小数目。
如果无法分割,则输出 0。

【输入形式】
程序先读入两个整数 m n 用空格分割 (m,n<10)。
表示表格的宽度和高度。
接下来是n行,每行m个正整数,用空格分开。每个整数不大于10000。

【输出形式】
输出一个整数,表示在所有解中,包含左上角的分割区可能包含的最小的格子数目。
【样例输入】

3 3
10 1 52
20 30 1
1 2 3

【样例输出】

3
dfs

m,n=map(int,input().split())
p=[]
for i in range(n):
    p.append(list(map(int,input().split())))
use=[[0 for i in range(m)]for j in range(n)]
dx=[0,0,-1,1]
dy=[-1,1,0,0]

ans=100

def dfs(x,y,s,res):
    global ans
    global b
    global use
    if s==b:
        if res<ans:
            ans=res
    else:
        for i in range(4):
            x+=dx[i]
            y+=dy[i]
            res+=1
            if x>=0 and x<n and y>=0 and y<m and res<=ans and use[x][y]==0:
                s+=p[x][y]
                use[x][y]=1
                if  s<=b:
                    dfs(x,y,s,res)
                s-=p[x][y]
                use[x][y]=0
            res-=1
            x-=dx[i]
            y-=dy[i]            

a=0
for i in range(n):
    for j in range(m):
        a+=p[i][j]
b=a//2
s0=p[0][0]
use[0][0]=1
if a%2==0:
    dfs(0,0,s0,1)
else:
    ans=0
print(ans)

递归:

while True:
    try:
        # n行m列
        m, n = map(int, input().split())
        s = []
        Sum = 0
        for i in range(n):
            s.append(list(map(int, input().split())))
            Sum += sum(s[i])
        used = [[0 for i in range(m)] for j in range(n)]
        ans = 100


        def dfs(i, j, temp_sum, cnt):
            global ans
            if temp_sum > Sum // 2:
                return
            if temp_sum == Sum // 2:
                ans = min(ans, cnt)
                return

            used[i][j] = 1
            # 如果现在不是最后一行,那么可以往下走
            if i + 1 < n and used[i+1][j] == 0:
                dfs(i + 1, j, temp_sum + s[i][j], cnt + 1)
            # 如果现在不是最顶上的一行,那么可以往上走
            if i - 1 >= 0 and used[i - 1][j] == 0:
                dfs(i - 1, j, temp_sum + s[i][j], cnt + 1)
            # 如果现在不是最左边的一列,那么可以往左边走
            if j - 1 >= 0 and used[i][j - 1] == 0:
                dfs(i, j - 1, temp_sum + s[i][j], cnt + 1)
            # 如果现在不是最右边的一列,那么可以往右边走
            if j + 1 < m and used[i][j + 1] == 0:
                dfs(i, j + 1, temp_sum + s[i][j], cnt + 1)

            # 执行到这说明s[i][j]这个数字不行,还原为未使用状态
            used[i][j] = 0


        dfs(0, 0, 0, 0)
        if ans<100:
            print(ans)
        else:
            print(0)
    except:
        break


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值