游游的you矩阵

发布于:2024-04-19 ⋅ 阅读:(27) ⋅ 点赞:(0)

题目:
游游拿到了一个字符矩阵,她想知道有多少个三角形满足以下条件:

  1. 三角形的三个顶点分别是 y、o、u 字符。
  2. 三角形为直角三角形,且两个直角边一个为水平、另一个为垂直。

输入描述:
第一行输入两个正整数n,m,用空格隔开,代表矩阵的行数和列数。
接下来的n行,每行输入一个长度为m的字符串,代表游游拿到的矩阵。
1 <=n,m <=1000
输出描述:
输出一个整数,代表满足条件的三角形个数。
示例1
输入例子:
2 3
you
our
输出例子:
3
例子说明:
如下图

在这里插入图片描述

我的思路:

这道题我的思路是先找出三个字符中数量最少的两个字符,然后在讨论这两个字符可能组合成水平,垂直以及斜边的情况,以此来判断符合直角三角的另一个字符,若符合,则计数加1。

我的代码如下:

def count_triangles(matrix):
    n = len(matrix)
    m = len(matrix[0])
    count = 0
    char_info = []  # 存储字符数量和位置集合的列表

    for char in ["y", "o", "u"]:
        positions = set()
        row_counts = [0] * n
        col_counts = [0] * m

        for i in range(n):
            for j in range(m):
                if matrix[i][j] == char:
                    positions.add((i, j))
                    row_counts[i] += 1
                    col_counts[j] += 1

        if positions:  # 检查字符在矩阵中是否存在
            char_info.append((char, len(positions), positions, row_counts, col_counts))

    if len(char_info) < 3:
        return 0  # 如果字符数量小于3,无法构成三角形,直接返回0

    # 按字符数量排序
    sorted_chars = sorted(char_info, key=lambda x: x[1])

    # 找到字符对应的位置集合和行列计数
    char1_positions, char1_row_counts, char1_col_counts = (
        sorted_chars[0][2],
        sorted_chars[0][3],
        sorted_chars[0][4],
    )
    char2_positions, char2_row_counts, char2_col_counts = (
        sorted_chars[1][2],
        sorted_chars[1][3],
        sorted_chars[1][4],
    )
    char3_positions, char3_row_counts, char3_col_counts = (
        sorted_chars[2][2],
        sorted_chars[2][3],
        sorted_chars[2][4],
    )

    for char1_i, char1_j in char1_positions:
        for char2_i, char2_j in char2_positions:
            if char2_i == char1_i:
                count += char3_col_counts[char1_j] + char3_col_counts[char2_j]
            elif char2_j == char1_j:
                count += char3_row_counts[char1_i] + char3_row_counts[char2_i]
            else:
                if (char1_i, char2_j) in char3_positions:
                    count += 1
                if (char2_i, char1_j) in char3_positions:
                    count += 1

    return count


n, m = map(int, input().split())
matrix = [input() for _ in range(n)]
result = count_triangles(matrix)
print(result)

但是这段代码始终怎么优化都不能全部AC,如果有更好的优化算法可以在评论区跟我说