本地运行或平台单样例运行无错误,提交后却报错。
本文以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作为返回来判定搜索是否终止。