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
Approach
Java
public class SpecialPositionsBinaryMatrix {public static void main(String[] args) {int mat[][] = { { 1, 0, 0 }, { 0, 0, 1 }, { 1, 0, 0 } };System.out.println(numSpecial(mat));}// function to count the special position in// binary matrixstatic int numSpecial(int[][] mat) {int n = mat.length;int m = mat[0].length;int cnt = 0;for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {if (mat[i][j] == 1) {int flag = 0;for (int k = 0; k < m; k++) {if (k != j) {if (mat[i][k] != 0) {flag = 1;break;}}}if (flag == 0) {for (int k = 0; k < n; k++) {if (k != i) {if (mat[k][j] != 0) {flag = 1;break;}}}}if (flag == 0)cnt++;}}}return cnt;}}
C++
#include <bits/stdc++.h>using namespace std;//function to count the special position in//binary matrixint numSpecial(vector<vector<int>>& mat){int n=mat.size(),m=mat[0].size();int cnt=0;for(int i=0;i<n;i++){for(int j=0;j<m;j++){if(mat[i][j]==1){int flag=0;for(int k=0;k<m;k++){if(k!=j){if(mat[i][k]!=0){flag=1;break;}}}if(flag==0){for(int k=0;k<n;k++){if(k!=i){if(mat[k][j]!=0){flag=1;break;}}}}if(flag==0)cnt++;}}}return cnt;}int main(){vector<vector<int>> mat = {{1,0,0},{0,0,1},{1,0,0}};cout<<numSpecial(mat);return 0;}
No comments:
Post a Comment