OD 算法题 B卷 【需要打开多少监视器】
文章目录
- 需要打开多少监视器
需要打开多少监视器
- 某长方形停车场,每个车位上方都有对应监控器,在当前车位和前后左右四个方向任意一个车位范围停车时,监控器才需要打开。
- 给出某一时刻停车场的停车分布,统计最少需要打开多少个监控器;
输入描述:
第一行输入m,n表示长宽;
后面输入m行,每行有n个0/1,1表示有停车;
输出描述:
最少需要打开的监控器的数量
示例1:
输入:
3 3
0 0 0
0 1 0
0 0 0
输出:
5
示例2:
输入:
5 6
1 0 0 0 1 1
0 0 1 1 0 1
0 0 1 1 1 1
1 0 0 0 1 0
0 0 0 0 0 0
输出:
26
python实现:
思路:
- 遍历m行n列,判断每个位置的监控是否需要打开;
- 当前位置+四个方向,任意一个位置有1则需要打开该位置的监控;
# 输入行 列
m, n = [int(x) for x in input().split()]# 输入停车分布
arr = []
for i in range(m):arr.append([int(x) for x in input().split()])# 遍历每个位置
result = 0
for i in range(m):for j in range(n):if arr[i][j] != 1:# 如果当前不为1,则判断四个方向的情况left = (j-1 >= 0) and arr[i][j-1] == 1right = (j+1 < n) and matrix[i][j+1] == 1top = (i-1 >= 0) and matrix[i-1][j] == 1bottom = (i+1 < m) and matrix[i+1][j] == 1if any([left, right, top, bottom]):result += 1else:# 当前位置为1,则直接打开监控result += 1print(result)