【学生方阵】学校组织活动,将学生排成一个矩形方阵。请在矩形方阵中找到最大的位置相连的男生数量。这个相连位置在一个直线上,方向可以是水平的、垂直
的、呈对角线的或者反对角线的。输出一个整数,表示矩阵中最长的位置相连的男生个数。
注:学生个数不会超过10000."
输入
3,4
F,M,M,F
F,M,M,F
F,F,F,M
输出
3
# 思想: dfs
def find_longest_male(people: List[List[str]], x: int, y: int, max_count: int, op_type: int, res: List[int]) -> int:
"""
:param people: 人数阵列
:param x: 行坐标
:param y: 列坐标
:param max_count: 最长连接长度
:param op_type: 操作类型: -1 程序入口, 0横 1竖 2撇 3捺
:param res: 结果存储列表
:return:
"""
# 终止条件
if x >= len(people) or x < 0 or y >= len(people[0]) or y < 0:
return max_count
if op_type != -1:
if people[x][y] == "M":
# 横
if op_type == 0:
return find_longest_male(people, x, y+1, max_count+1, op_type, res)
# 竖
if op_type == 1:
return find_longest_male(people, x+1, y, max_count+1, op_type, res)
# 撇
if op_type == 2:
return find_longest_male(people, x+1, y-1, max_count+1, op_type, res)
# 捺
if op_type == 3:
return find_longest_male(people, x+1, y+1, max_count+1, op_type, res)
else:
return max_count
# 四种方向检查, 横竖撇捺, 0123
for row in range(len(people)):
for col in range(len(people[row])):
# 跳过F
if people[row][col] == "F":
continue
res.append(
max(
# 横
find_longest_male(people, row, col, 0, 0, res),
# 竖
find_longest_male(people, row, col, 0, 1, res),
# 撇
find_longest_male(people, row, col, 0, 2, res),
# 捺
find_longest_male(people, row, col, 0, 3, res)
)
)
return max(res)
if __name__ == '__main__':
_people = [
["M", "M", "M", "M"],
["F", "M", "M", "F"],
["F", "F", "F", "M"],
]
_res = []
print(find_longest_male(_people, 0, 0, 0, -1, _res))