Count number of 1's at specific position in a Matrix
Last Updated :
24 Apr, 2023
Given a binary matrix mat[][] of size m*n (0-based indexing), find the number of 1's such that 1 is located at a specific position where the same row and same column don't have any other 1's.
Examples:
Input: mat[][] = [[0, 0, 1], [0, 1, 0], [1, 0, 0]]
Output: 3
Explanation: All 1's in the matrix satisfy the given condition.
Input: mat[][] = [[1, 0, 1], [0, 1, 0], [1, 0, 0]]
Output: 1
Explanation: mat[1][1] satisfy the given condition.
Approach: The approach is based on matrix traversal.
Below are the steps for the above approach:
- Initialize auxiliary array rows[] and cols[] to track how many 1's are in the corresponding row or column.
- Initialize a variable say, ans to store the number of 1's that satisfy the given condition.
- Now traverse through the matrix mat[][] and check if mat[i][j]==1 then increment rows[i]++(for row) and increment cols[j]++(for column).
- Run a loop from i = 0 to i < m and check if row[i] == 1,
- Run a loop from j = 0 to j < n, and check if the element at the current position is 1 in mat[][] if mat[i][j] == 1
- Check if cols[j] == 1, increment ans, else break.
- Return ans.
Below is the code for the above approach:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
int findNumberOfOnes(vector<vector<char> >& mat)
{
const int m = mat.size();
const int n = mat[0].size();
int ans = 0;
// Auxiliary row and col for tracking
// how many B at that corresponding
// row and col
vector<int> rows(m);
vector<int> cols(n);
// Traversing through the mat[][]
// matrix. If mat[i][j] == B then
// increment rows[i]++(for row) and
// increment cols[j]++(for column).
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (mat[i][j] == 1) {
++rows[i];
++cols[j];
}
// Traversing through the mat[][]
// matrix again and if
// rows[i]==1 || cols[j]==1
// then ans++, else continue.
for (int i = 0; i < m; ++i)
if (rows[i] == 1)
for (int j = 0; j < n; ++j)
// If the current position
// is 1 in this row then
// break and search
// the next row
if (mat[i][j] == 1) {
if (cols[j] == 1)
++ans;
break;
}
return ans;
}
// Drivers code
int main()
{
vector<vector<char> > mat
= { { 0, 0, 1 }, { 0, 1, 0 }, { 1, 0, 0 } };
// Function Call
cout << findNumberOfOnes(mat);
return 0;
}
Java
/*package whatever // do not write package name here */
// A program for finding the lonely color
import java.io.*;
class GFG {
public static int findLonelyColor(char[][] painting)
{
int m = painting.length, n = painting[0].length;
// Auxiliary row and col for tracking how many B at
// that corresponding row and col
int[] rows = new int[m];
int[] cols = new int[n];
// Traversing through the painting matrix. If
// painting[i][j]==B then increment rows[i]++(for
// row) and increment cols[j]++(for column).
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (painting[i][j] == 'B') {
rows[i]++;
cols[j]++;
}
}
}
int ans = 0;
// Traversing through the painting matrix again and
// if rows[i]==1 || cols[j]==1 then ans++, else
// continue.
for (int i = 0; i < m; ++i) {
if (rows[i] == 1) {
for (int j = 0; j < n; ++j) {
// If the current position is 'B' in this
// row then break and search the next
// row
if (painting[i][j] == 'B'
&& cols[j] == 1) {
ans++;
break;
}
}
}
}
return ans;
}
public static void main(String[] args)
{
char[][] painting = { { 'W', 'W', 'B' },
{ 'W', 'B', 'W' },
{ 'B', 'W', 'W' } };
int ans = findLonelyColor(painting);
System.out.println(ans);
}
}
Python3
# A program for finding the lonely color
from typing import List
def findLonelyColor(self, painting: List[List[str]]) -> int:
# Auxiliary row and col for tracking how many B at that
# corresponding row and col
m, n = len(painting), len(painting[0])
rows, cols = [0] * m, [0] * n
# Traversing through the painting matrix.
# If painting[i][j]== B then increment rows[i]++(for row)
# and increment cols[j]++(for column).
for i in range(m):
for j in range(n):
if painting[i][j] == 'B':
rows[i] += 1
cols[j] += 1
ans = 0
# Traversing through the painting matrix again and
# if rows[i]== 1 || cols[j]== 1 then ans++, else continue
for i in range(m):
if rows[i] == 1:
for j in range(n):
# If the current position is 'B' in this row
# then break and search the next row
if painting[i][j] == 'B' and cols[j] == 1:
ans += 1
break
return ans
if __name__ == "__main__":
painting = [['W', 'W', 'B'],
['W', 'B', 'W'],
['B', 'W', 'W']]
print(findLonelyColor(__name__, painting))
C#
using System;
public class GFG {
public static int FindLonelyColor(char[, ] painting)
{
int m = painting.GetLength(0);
int n = painting.GetLength(1);
// Auxiliary row and col for tracking how many B at
// that corresponding row and col
int[] rows = new int[m];
int[] cols = new int[n];
// Traversing through the painting matrix. If
// painting[i,j] == 'B' then increment rows[i]++(for
// row) and increment cols[j]++(for column).
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (painting[i, j] == 'B') {
rows[i]++;
cols[j]++;
}
}
}
int ans = 0;
// Traversing through the painting matrix again and
// if rows[i]==1 || cols[j]==1 then ans++, else
// continue.
for (int i = 0; i < m; ++i) {
if (rows[i] == 1) {
for (int j = 0; j < n; ++j) {
// If the current position is 'B' in this
// row then break and search the next
// row
if (painting[i, j] == 'B'
&& cols[j] == 1) {
ans++;
break;
}
}
}
}
return ans;
}
public static void Main()
{
char[, ] painting = { { 'W', 'W', 'B' },
{ 'W', 'B', 'W' },
{ 'B', 'W', 'W' } };
int ans = FindLonelyColor(painting);
Console.WriteLine(ans);
}
}
// This code is contributed by Prajwal Kandekar
JavaScript
// JavaScript code for the above approach:
function findNumberOfOnes(mat) {
const m = mat.length;
const n = mat[0].length;
let ans = 0;
// Auxiliary row and col for tracking
// how many B at that corresponding
// row and col
const rows = new Array(m).fill(0);
const cols = new Array(n).fill(0);
// Traversing through the mat[][]
// matrix. If mat[i][j] == B then
// increment rows[i]++(for row) and
// increment cols[j]++(for column).
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
if (mat[i][j] === 1) {
++rows[i];
++cols[j];
}
}
}
// Traversing through the mat[][]
// matrix again and if
// rows[i]==1 || cols[j]==1
// then ans++, else continue.
for (let i = 0; i < m; ++i) {
if (rows[i] === 1) {
for (let j = 0; j < n; ++j) {
// If the current position
// is 1 in this row then
// break and search
// the next row
if (mat[i][j] === 1) {
if (cols[j] === 1) {
++ans;
}
break;
}
}
}
}
return ans;
}
// Drivers code
const mat = [
[0, 0, 1],
[0, 1, 0],
[1, 0, 0],
];
// Function Call
console.log(findNumberOfOnes(mat));
Output :
3
Time Complexity: O(m*n + m*n), Where m and n are the sizes of rows and columns
Auxiliary Space: O(m + n), used auxiliary array rows and cols of size m and n respectively
Similar Reads
Count number of 1's at specific position in a matrix - II Given a binary matrix mat[][] of size m*n (0-based indexing), the task is to return the total number of 1's in the matrix that follows the below two rules. i.e: Row R and column C both contain exactly N number of 1's.All rows with 1's in column C should be the same as the 1's present in row R.Exampl
13 min read
Count number of free cell present in the Matrix Given a Matrix size N*N and an integer K. Initially, the matrix contains only 0. You are given K tasks and for each task, you are given two coordinates (r, c). Where coordinates (r, c) denotes the rth row and the cth column of the given matrix. You have to perform each task sequentially in the given
11 min read
Count number of ways to reach a given score in a Matrix Given a N x N matrix mat[][] consisting of non-negative integers, the task is to find the number of ways to reach a given score M starting from the cell (0, 0) and reaching the cell (N - 1, N - 1) by going only down(from (i, j) to (i + 1, j)) or right(from (i, j) to (i, j + 1)). Whenever a cell (i,
8 min read
Count number of ways to reach a given score in a Matrix Given a N x N matrix mat[][] consisting of non-negative integers, the task is to find the number of ways to reach a given score M starting from the cell (0, 0) and reaching the cell (N - 1, N - 1) by going only down(from (i, j) to (i + 1, j)) or right(from (i, j) to (i, j + 1)). Whenever a cell (i,
8 min read
Count of numbers in given range L to R which are present in a Matrix Given a matrix(mat[][]), which is sorted row and column-wise in increasing order. Two integers are given, L and R, our task is to count number of elements of the matrix within the range [L, R].Examples: Input: L = 3, R = 11, matrix = {{1, 6, 9} {2, 7, 11} {3, 8, 12}} Output: 6 Explanation: The eleme
8 min read
Count of numbers in given range L to R which are present in a Matrix Given a matrix(mat[][]), which is sorted row and column-wise in increasing order. Two integers are given, L and R, our task is to count number of elements of the matrix within the range [L, R].Examples: Input: L = 3, R = 11, matrix = {{1, 6, 9} {2, 7, 11} {3, 8, 12}} Output: 6 Explanation: The eleme
8 min read