. - 力扣(LeetCode)

由题意得当矩阵中grid[i][j]为1时,判断该位置能组成多少直角三角形的算法为: (i行为1的数量-1)*(j列为1的数量-1)

from typing import List
 
 
class Solution:
	def numberOfRightTriangles(self, grid: List[List[int]]) -> int:
		count = 0
		# 统计每一行有多少个1
		row_counts = [sum(row) for row in grid]
		# 统计每一列有多少个1
		col_counts = [sum(grid[i][j] for i in range(len(grid))) for j in range(len(grid[0]))]
		
		for i in range(len(grid)):
			for j in range(len(grid[0])):
				if grid[i][j] == 1:
					count += (row_counts[i] - 1) * (col_counts[j] - 1)
		return count