有关蓝桥杯段错误的问题

本地运行或平台单样例运行无错误,提交后却报错。

本文以Python为例,

很可能是因为代码中出现了exit()终止函数的问题

(见以下代码row:24,38中exit(0)函数)

import os
import sys

# 请在此输入您的代码
n = int(input())
cols = list(map(int, input().split())) if n else []
rows = list(map(int, input().split())) if n else []
DIRS = [(1, 0), (-1, 0), (0, -1), (0, 1)]
arr = []

used = [[False] * n for _ in range(n)]
def ok(i, j):
    return i >= 0 and j >= 0 and i < n and j < n and not used[i][j]

def dfs(x, y, sm):
    rows[x] -= 1
    cols[y] -= 1
    sm-=2
    used[x][y] = True
    arr.append(x * n + y)
    if x == y == n - 1:
        if not sm:
            print(' '.join(list(str(a) for a in arr)))
            exit(0)
    else:
        for dx, dy in DIRS:
            if ok(x+dx, y+dy) and rows[x+dx] and cols[y+dy]:
                dfs(x + dx, y + dy, sm)
    rows[x] += 1
    cols[y] += 1
    sm+=2
    used[x][y] = False
    arr.pop()

if n:
    dfs(0, 0, sum(rows) + sum(cols))
else:
    exit(0)

修改为以下代码则无段错误

import os
import sys

# 请在此输入您的代码
n = int(input())
cols = list(map(int, input().split())) if n else []
rows = list(map(int, input().split())) if n else []
DIRS = [(1, 0), (-1, 0), (0, -1), (0, 1)]
arr = []

used = [[False] * n for _ in range(n)]
def ok(i, j):
    return i >= 0 and j >= 0 and i < n and j < n and not used[i][j]

def dfs(x, y, sm):
    rows[x] -= 1
    cols[y] -= 1
    sm-=2
    used[x][y] = True
    arr.append(x * n + y)
    if x == y == n - 1:
        if not sm:
            print(' '.join(list(str(a) for a in arr)))
            return True
    else:
        for dx, dy in DIRS:
            if ok(x+dx, y+dy) and rows[x+dx] and cols[y+dy] and dfs(x + dx, y + dy, sm):
                return True
    rows[x] += 1
    cols[y] += 1
    sm+=2
    used[x][y] = False
    arr.pop()
    return False

if n:
    dfs(0, 0, sum(rows) + sum(cols))

即使用exit()作为跳出会导致段错误,代码会根据样例数多次运行,不能执行一部分样例就中断,建议使用布尔值bool作为返回来判定搜索是否终止。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值