[LeetCode] 1582. Special Positions in a Binary Matrix

Given a rows x cols matrix mat, where mat[i][j] is either 0 or 1, return the number of special positions in mat.

A position (i,j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed).

Example 1:

Input: mat = [[1,0,0],
              [0,0,1],
              [1,0,0]]
Output: 1
Explanation: (1,2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.

Example 2:

Input: mat = [[1,0,0],
              [0,1,0],
              [0,0,1]]
Output: 3
Explanation: (0,0), (1,1) and (2,2) are special positions. 

Example 3:

Input: mat = [[0,0,0,1],
              [1,0,0,0],
              [0,1,1,0],
              [0,0,0,0]]
Output: 2

Example 4:

Input: mat = [[0,0,0,0,0],
              [1,0,0,0,0],
              [0,1,0,0,0],
              [0,0,1,0,0],
              [0,0,0,1,1]]
Output: 3

Constraints:

  • rows == mat.length
  • cols == mat[i].length
  • 1 <= rows, cols <= 100
  • mat[i][j] is 0 or 1.

二进制矩阵中的特殊位置。

题意是找二进制矩阵中的特殊位置。这个特殊位置的定义是如果当前坐标值是1且他是当前行和当前列唯一的1,则当前位置就是一个特殊位置。

这道题不涉及算法,思路是需要扫描两遍矩阵。第一遍扫描的时候我们需要额外创建两个数组,一个记录当前行有多少个1,一个记录当前列有多少个1。第二遍扫描的时候,再碰到1的时候,我们就去看这个位置所在的行和所在的列是不是都只有一个1,如果是,则说明这是一个满足题意的特殊位置。

时间O(mn)

空间O(n)

Java实现

 1 class Solution {
 2     public int numSpecial(int[][] mat) {
 3         int m = mat.length;
 4         int n = mat[0].length;
 5         int[] rows = new int[m];
 6         int[] cols = new int[n];
 7         for (int i = 0; i < m; i++) {
 8             for (int j = 0; j < n; j++) {
 9                 if (mat[i][j] == 1) {
10                     rows[i]++;
11                     cols[j]++;
12                 }
13             }
14         }
15 
16         int count = 0;
17         for (int i = 0; i < m; i++) {
18             for (int j = 0; j < n; j++) {
19                 if (mat[i][j] == 1 && rows[i] == 1 && cols[j] == 1) {
20                     count++;
21                 }
22             }
23         }
24         return count;
25     }
26 }

这道题还有DFS的思路,如果有兴趣可以参见这个帖子

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/13972074.html