【学生方阵】学校组织活动,将学生排成一个矩形方阵。请在矩形方阵中找到最大的位置相连的男生数量。这个相连位置在一个直线上,方向可以是水平的、垂直的、呈对角线的或者反对角线的。

【学生方阵】学校组织活动,将学生排成一个矩形方阵。请在矩形方阵中找到最大的位置相连的男生数量。这个相连位置在一个直线上,方向可以是水平的、垂直
的、呈对角线的或者反对角线的。输出一个整数,表示矩阵中最长的位置相连的男生个数。
注:学生个数不会超过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))

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值