Finding a minimal set of rectangles covering a binary matrix [duplicate] - algorithm

This question already has answers here:
Algorithm for finding the fewest rectangles to cover a set of rectangles without overlapping
(2 answers)
Closed 5 years ago.
Say I have the following binary matrix:
0 0 0 1 1 1 0
0 0 0 1 1 1 0
0 0 0 1 1 1 0
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
0 0 0 1 1 1 0
0 0 0 1 1 1 0
0 0 0 1 1 1 0
I want to find the set of rectangles parallel to the x and y axis that covers every 1 at least once and covers not a single 0 which has minimal cardinality (the least amount of rectangles). In the example above this would be the rectangles ((0, 3), (6, 5)) and ((3, 0), (5, 8)) (notation is in the form (topleft, bottomright)) - the minimal solution is using two rectangles.
My previous attempt was finding the rectangle with the largest area covering only 1's, adding that rectangle to the set and then marking all those 1's as 0's, until all 1's are gone. While this set would cover every 1 and not a single 0, it won't necessarily have minimal cardinality (this algorithm will fail on the example above).

I think you should replace covered 1's with 2's instead of 0's. This way you can include the 2's when covering 1's and still not cover any 0's.
Here's what I came up with:
#include <stdio.h>
#include <stdlib.h>
struct board {
int **data;
int w,h;
};
int load_board(char *, struct board *);
void print_board(struct board *);
int max_height_with_fixed_w(struct board *board, int i, int j, int w) {
int jj = -1, ii;
if (board->data[j][i] != 0) {
for (jj = j; jj < board->h && board->data[jj][i] != 0; jj++) {
for (ii = i; ii - i < w; ii++) {
if (board->data[jj][ii] == 0)
return jj - j;
}
}
printf("maximum height = %d\n", jj);
}
return jj - j;
}
void find_largest_rect_from(
struct board *board,
int i, int j, int *ei, int *ej) {
int max_w = 0, max_h = 0, max_a = 0;
*ei = *ej = -1;
for (max_w = 0; max_w < board->w - i &&
(board->data[j][i + max_w] != 0);
max_w++) {
int max_aa;
int max_hh = max_height_with_fixed_w(board, i, j, max_w + 1);
if (max_hh > max_h) {
max_h = max_hh;
}
max_aa = max_hh * (max_w + 1);
printf(" area: %d x %d = %d\n", max_hh, max_w + 1, max_aa);
if (max_aa > max_a) {
max_a = max_aa;
*ei = i + max_w;
*ej = j + max_hh - 1;
}
}
printf("max width : %d\n", max_w);
printf("max height: %d\n", max_h);
printf("max area : %d\n", max_a);
}
int main(int arc, char **argv) {
struct board board;
int jj, ii, i = 0, j = 0;
int total_rects = 0;
if(load_board(argv[1], &board)) return 1;
print_board(&board);
for (j = 0; j < board.h; j++) {
for (i = 0; i < board.w; i++) {
if (board.data[j][i] == 1) {
find_largest_rect_from(&board, i, j, &ii, &jj);
printf("largest from %d, %d ends at %d,%d\n", i, j, ii, jj);
int marki, markj;
total_rects++;
for (markj = j; markj <= jj; markj++) {
for (marki = i; marki <= ii; marki++) {
board.data[markj][marki] = 2;
}
}
print_board(&board);
}
}
}
printf("minimum %d rects are required\n", total_rects);
return 0;
}
int load_board(char *fname, struct board *board) {
FILE *file = fopen(fname, "r");
int j,i;
if (!file) return 1;
fscanf(file, "%d %d", &board->w, &board->h);
board->data = (int**)malloc(sizeof(int*)*board->h);
for (j = 0; j < board->h; j++) {
board->data[j] = (int*)malloc(sizeof(int)*board->w);
for (i = 0; i < board->w; i++) {
fscanf(file, "%d", &board->data[j][i]);
}
}
return 0;
}
void print_board(struct board *board) {
int i,j;
printf("board size: %d, %d\n", board->w, board->h);
for (j = 0; j < board->h; j++) {
for (i = 0; i < board->w; i++) {
printf("%d ", board->data[j][i]);
} printf("\n");
}
}
Example input 1:
7 9
0 0 0 1 1 1 0
0 0 0 1 1 1 0
0 0 0 1 1 1 0
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
0 0 0 1 1 1 0
0 0 0 1 1 1 0
0 0 0 1 1 1 0
Example input 2:
7 7
0 0 0 1 0 0 0
0 0 1 1 1 0 0
0 1 1 1 1 1 0
1 1 1 1 1 1 1
0 1 1 1 1 1 0
0 0 1 1 1 0 0
0 0 0 1 0 0 0

Idea for an algorithm:
As long as there are 1s in the matrix do:
For every 1 that doesn't have 1 above it AND doesn't have 1 to its left, do:
Go greedy: start from this 1 and go in diagonal to the right and down, as long as there are 1s on the way - create a rectangle and change the 1s of the created rectangle into 0s.

I'd go for an algorithm that picks points and expands until it comsumed all possible space, and then picks more, until all points on the grid have been consumed.
For your example, say we're consuming 1s.
I'll pick (0,3), the uppermost of the leftmost 1s. My rectangle would start at a size of 0,0. I'd expand it right and down until it grew to a size of 6,2. At this point, I'd mark those points as occupied.
I'd then pick another point, say (3,0), with a rectangle of size 0,0. I'd grow it down and right until it took up the largest available space, at a size of 2,6.
Consider the following:
0 0 0 1 0 0 0
0 0 1 1 1 0 0
0 1 1 1 1 1 0
1 1 1 1 1 1 1
0 1 1 1 1 1 0
0 0 1 1 1 0 0
0 0 0 1 0 0 0
You can easily determine that for any random starting points, it will always take 4 rectangles.
In order to mark points as "occupied", you should mark them differently than those marked "unconsumable". You can then differentiate between unconsumable (which cannot be expanded into) and "occupied" (which may be expanded into, but do not have to be since they already have been).

Related

How would one solve the staircase problem recursively with a variable number of steps?

The problem of determining the n amount of ways to climb a staircase given you can take 1 or 2 steps is well known with the Fibonacci sequencing solution being very clear. However how exactly could one solve this recursively if you also assume that you can take a variable M amount of steps?
I tried to make a quick mockup of this algorithm in typescript with
function counter(n: number, h: number){
console.log(`counter(n=${n},h=${h})`);
let sum = 0
if(h<1) return 0;
sum = 1
if (n>h) {
n = h;
}
if (n==h) {
sum = Math.pow(2, h-1)
console.log(`return sum=${sum}, pow(2,${h-1}) `)
return sum
}
for (let c = 1; c <= h; c++) {
console.log(`c=${c}`)
sum += counter(n, h-c);
console.log(`sum=${sum}`)
}
console.log(`return sum=${sum}`)
return sum;
}
let result = counter (2, 4);
console.log(`result=${result}`)
but unfortunately this doesn't seem to work for most cases where the height is not equal to the number of steps one could take.
I think this could be solved with recursive DP.
vector<vector<int>> dp2; //[stair count][number of jumps]
int stair(int c, int p) {
int& ret = dp2[c][p];
if (ret != -1) return ret; //If you've already done same search, return saved result
if (c == n) { //If you hit the last stair, return 1
return ret = 1;
}
int s1 = 0, s2 = 0;
if (p < m) { //If you can do more jumps, make recursive call
s1 = stair(c + 1, p + 1);
if (c + 2 <= n) { //+2 stairs can jump over the last stair. That shouldn't happen.
s2 = stair(c + 2, p + 1);
}
}
return ret = s1 + s2; //Final result will be addition of +1 stair methods and +2 methods
}
int main()
{
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n >> m; dp2 = vector<vector<int>>(n + 1, vector<int>(m + 1, -1));
for (int i = 1; i <= m; i++) {
dp2[n][i] = 1; //All last stair method count should be 1, because there is no more after.
}
cout << stair(0, 0) << "\n";
return 0;
}
Example IO 1
5 5
8
// 1 1 1 1 1
// 1 1 1 2
// 1 1 2 1
// 1 2 1 1
// 2 1 1 1
// 1 2 2
// 2 1 2
// 2 2 1
Example IO 2
5 4
7
// 1 1 1 2
// 1 1 2 1
// 1 2 1 1
// 2 1 1 1
// 1 2 2
// 2 1 2
// 2 2 1
Example IO 3
5 3
3
// 1 2 2
// 2 1 2
// 2 2 1

How to calculate cost to Convert an N X M binary matrix to all 0 matrix with only allowed moves as square-matrix toggle?

Given an N X M binary matrix ( every element is either 1 or 0) , find the minimum number of moves to convert it to an all 0 matrix.
For converting a matrix, one can choose squares of any size and convert the value of that square. '1' changes to '0' and '0' changes to '1'.This process can be done multiple times with square of the same size. Converting any square counts as 1 move.
Calculate minimum number of moves required..
Example :
input matrix
0 1 1
0 0 0
0 1 1
we need to calculate minimum moves to convert this to all '0' matrix
0 0 0
0 0 0
0 0 0
Here,
For square of size 1 ( 1 X 1 or single element sub-matrix), the total number of moves required to convert this matrix is 4 . he converts elements for position (1,2),(1,3),(3,2),(3,3)
For square of size 2 ( 2 X 2 or single element sub-matrix), it takes 2 moves to convert the matrix
First we can convert elements from (1,2) to (2,3) and the matrix becomes, {{0 0 0}, {0 1 1}, {0 1 1}}
And then we convert elements from (2,2)to (3,3) and the matrix becomes ``{{0 0 0}, {0 0 0}, {0 0 0}}```
So minimum is 2.
Could some help in designing an approach to this ?
I attempted to solve it using Gaussian elimination for every possible square size. But the result is not correct here. There must be some gap in my approach to this problem.
package com.practice.hustle;
import java.util.Arrays;
public class GaussianElimination {
public static void main(String[] args) {
int countMoves = Integer.MAX_VALUE;
byte[][] inputMatrix = new byte[3][3];
inputMatrix[0][0] = 0;
inputMatrix[0][1] = 1;
inputMatrix[0][2] = 1;
inputMatrix[1][0] = 0;
inputMatrix[1][1] = 0;
inputMatrix[1][2] = 0;
inputMatrix[2][0] = 0;
inputMatrix[2][1] = 1;
inputMatrix[2][2] = 1;
int N = inputMatrix.length;
int M = inputMatrix[0].length;
int maxSize = Math.min(N, M);
for (int j = 2; j <= maxSize; ++j) { // loop for every possible square size
byte[][] a = new byte[N * M][(N * M) + 1];
for (int i = 0; i < N * M; i++) { // logic for square wise toggle for every element of N*M elements
byte seq[] = new byte[N * M + 1];
int index_i = i / M;
int index_j = i % M;
if (index_i <= N - j && index_j <= M - j) {
for (int c = 0; c < j; c++) {
for (int k = 0; k < j; k++) {
seq[i + k + M * c] = 1;
}
}
a[i] = seq;
} else {
if (index_i > N - j) {
seq = Arrays.copyOf(a[i - M], N * M + 1);
} else {
seq = Arrays.copyOf(a[i - 1], N * M + 1);
}
}
seq[N * M] = inputMatrix[index_i][index_j];
a[i] = seq;
}
System.out.println("\nSolving for square size = " + j);
print(a, N * M);
int movesPerSquareSize = gaussian(a);
if (movesPerSquareSize != 0) { // to calculate minimum moves
countMoves = Math.min(countMoves, movesPerSquareSize);
}
}
System.out.println(countMoves);
}
public static int gaussian(byte a[][]) {
// n X n+1 matrix
int N = a.length;
for (int k = 0; k < N - 1; k++) {
// Finding pivot element
int max_i = k, max_value = a[k][k];
for (int i = k + 1; i < N; i++) {
if (a[i][k] > max_value) {
max_value = a[i][k];
max_i = i;
}
}
// swap max row with kth row
byte[] temp = a[k];
a[k] = a[max_i];
a[max_i] = temp;
// convert to 0 all cells below pivot in the column
for (int i = k+1; i < N; i++) {
// int scalar = a[i][k] + a[k][k]; // probability of a divide by zero
if (a[i][k] == 1) {
for (int j = 0; j <= N; j++) {
if (a[i][j] == a[k][j]) {
a[i][j] = 0;
} else {
a[i][j] = 1;
}
}
}
}
}
System.out.println("\n\tAfter applying gaussian elimination : ");
print(a, N);
int count = 0;
for (int i = 0; i < N; i++) {
if (a[i][N] == 1)
++count;
}
return count;
}
private static void print(byte[][] a, int N) {
for (int i = 0; i < N; i++) {
System.out.print("\t ");
for (int j = 0; j < N + 1; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println(" ");
}
}
}
Its giving final reduced Euler matrix formed is incorrect and thereby the result is also incorrect.
I think its failing due to the logic used for element like - the cell at index-(2,3) , for that we are not sure which square would it be a part of ( either the square from (1,2) to (2,3) or the square from ( 2,2) to (3,3))
here the input matrix to Gaussian algo is having exactly same sequence at 2nd and 3rd row which could be the culprit of incorrect results.
1 1 0 1 1 0 0 0 0 0
* 0 1 1 0 1 1 0 0 0 1 *
* 0 1 1 0 1 1 0 0 0 1 *
0 0 0 1 1 0 1 1 0 0
0 0 0 0 1 1 0 1 1 0
0 0 0 0 1 1 0 1 1 0
0 0 0 1 1 0 1 1 0 0
0 0 0 0 1 1 0 1 1 1
0 0 0 0 1 1 0 1 1 1
for a sqaure size 2, the above program prints :
Solving for square size = 2
The input to Gaussian algo :
1 1 0 1 1 0 0 0 0 0
0 1 1 0 1 1 0 0 0 1
0 1 1 0 1 1 0 0 0 1
0 0 0 1 1 0 1 1 0 0
0 0 0 0 1 1 0 1 1 0
0 0 0 0 1 1 0 1 1 0
0 0 0 1 1 0 1 1 0 0
0 0 0 0 1 1 0 1 1 1
0 0 0 0 1 1 0 1 1 1
After applying gaussian elimination :
1 0 1 0 0 0 1 0 1 1
0 1 1 0 0 0 0 1 1 0
0 0 0 0 0 0 0 0 0 0
0 0 0 1 0 1 1 0 1 0
0 0 0 0 1 1 0 1 1 1
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 1

How to approach this two dimensional array problem?

Problem (THE QUESTION)
Strokes to paint
Alex wants to paint a picture. In one stroke, Alex can only paint the same colored cells which are joined via some edge.
Given the painting as a 2-dimensional array of letters indicating colors, determine the minimum number of strokes to completely paint the picture.
Example: The canvas height, h = 3 and width, w = 5 is to be painted with picture=["aabba", "aabba", "aaacb"]. The diagram below shows the 5 strokes needed to paint the canvas. It takes two strokes each for colors a and b, and one for c
a a b b a
a a b b a
a a a c b
Function Description Complete the function strokesRequired in the editor below. The function must return an integer, the minimum number of strokes required to paint the canvas.
strokesRequired has the following parameter(s): picture[picture[0],...picture[h-1]] an array of strings where each string represents one row of the picture to be painted
Constraints
1 <= h <= 10^5
1<= w <= 10^5
1 <= h*w <= 10^5
len(pictureffl) = w (where 0 <= i < h)
picture[i][j] <- (a, b, c) (where 0 <= i < h and 0 <= j < w)
Hello.. so i attended one company interview and they asked me this problem and iam not getting any ideas please help
class Paint:
def __init__(self, row, col, arr):
self.ROW = row
self.COL = col
self.arr = arr
def visit(self, i, j, visited):
ele = self.arr[i][j]
for k in range(i,self.ROW):
for l in range(j, self.COL):
if self.arr[k][l]==ele:
visited[k][l]=True
v=l
if l>0 and self.arr[k][l-1]==ele and not visited[k][l-1]:
self.visit(k, l-1, visited)
if k>0 and self.arr[k-1][l]==ele and not visited[k-1][l]:
self.visit(k-1, l, visited)
elif l>=v:
break
# 2D matrix
def count_cells(self):
# Make an array to mark visited cells.
# Initially all cells are unvisited
visited = [[False for j in range(self.COL)]for i in range(self.ROW)]
# Initialize count as 0 and travese
count = 0
for i in range(self.ROW):
for j in range(self.COL):
# If a cell value false then not visited yet
# then visit
if visited[i][j] == False:
# Visit all cells in the array
self.visit(i, j, visited)
print(visited)
count += 1
return count
arr = ["aabba", "aabba", "aaacb"]
row = len(arr)
col = len(arr[0])
p = Paint(row, col, arr)
print (p.count_cells())
function visit(picture, i, j, visitedBoxes) {
const currentElem = picture[i][j];
if (picture[i][j] === currentElem) {
visitedBoxes[i][j] = true;
// go in four directions
// south
if (i + 1 < picture.length && picture[i+1][j] === currentElem && visitedBoxes[i+1][j] === false) {
visit(picture, i+1, j, visitedBoxes);
}
// west
if (j+ 1 < picture[i].length && picture[i][j+1] === currentElem && visitedBoxes[i][j+1] === false) {
visit(picture, i, j+1, visitedBoxes);
}
// north
if (i > 0 && picture[i-1][j] === currentElem && visitedBoxes[i-1][j] === false) {
visit(picture, i-1, j, visitedBoxes);
}
// west
if (j > 0 && picture[i, j-1] === currentElem && visitedBoxes[i, j-1] === false) {
visit(picture, i, j-1, visitedBoxes);
}
}
}
function countStrokes(picture) {
const visitedBoxes = [];
for (let i = 0; i < picture.length; i++) {
visitedBoxes[i] = [];
for(let j = 0; j < picture[i].length; j++) {
visitedBoxes[i][j] = false;
}
}
let srokesCount = 0;
for (let i = 0; i < picture.length; i++) {
for (let j = 0; j < picture[i].length; j++) {
if (!visitedBoxes[i][j]) {
visit(picture, i, j, visitedBoxes);
srokesCount++;
}
}
}
console.log('Strokes Count', srokesCount);
}
countStrokes(['aaaba', 'ababa', 'aacba']);
This will output 5.
Also you can use
function printVisited(visitedBoxes) {
for (let i = 0; i < visitedBoxes.length; i++) {
let str = ''
for(let j = 0; j < visitedBoxes[i].length; j++) {
str += visitedBoxes[i][j] ? '1 ': '0 ';
}
console.log(str);
}
console.log('-------------');
}
to print after each loop.
Output
1 1 1 0 0
1 0 1 0 0
1 1 0 0 0
-------------
1 1 1 1 0
1 0 1 1 0
1 1 0 1 0
-------------
1 1 1 1 1
1 0 1 1 1
1 1 0 1 1
-------------
1 1 1 1 1
1 1 1 1 1
1 1 0 1 1
-------------
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
-------------
Strokes Count 5

Flood Fill Recursive algorithm

Hello I made use of flood fill recursive algorithm to find the connected cells to each other in an 2D array (Here I am using vectors). But this fails for one boundary test case
#include<iostream>
#include<vector>
using namespace std;
int count = 0;
int max_count = 0;
int min_count = 0;
void floodFillUtil(vector< vector<int> > &a,int i,int j,int m,int n,int prevP,int newN)
{
if (i<0 || i>= m || j<0 || j>=n)
return;
if(a[i][j] != prevP)
return;
count++;
a[i][j] = newN;
floodFillUtil(a,i+1,j+1,m,n,prevP,newN);
floodFillUtil(a,i-1,j-1,m,n,prevP,newN);
floodFillUtil(a,i-1,j+1,m,n,prevP,newN);
floodFillUtil(a,i+1,j-1,m,n,prevP,newN);
floodFillUtil(a,i+1,j,m,n,prevP,newN);
floodFillUtil(a,i,j+1,m,n,prevP,newN);
floodFillUtil(a,i-1,j,m,n,prevP,newN);
floodFillUtil(a,i,j-1,m,n,prevP,newN);
}
void floodFill(vector< vector<int> > &a,int i,int j,int newN,int m,int n) {
int prevP = a[i][j];
floodFillUtil(a,i,j,m,n,prevP,newN);
}
// Driver program to test above function
int main()
{ int m,n;
cin>>m>>n;
vector<vector<int> > a;
vector<int> b;
for(int i=0;i<m;i++)
{for(int j=0;j<n;j++)
{ int temp;
cin>>temp;
b.push_back(temp);
}
a.push_back(b);
b.clear();
}
for(int i=0;i<m;i++)
for(int j=0;j<n;j++) {
if (a[i][j] == 1){
floodFill(a,i,j,2+i,m,m);
min_count = count ;
if(min_count > max_count){
max_count = min_count;
}
count=0;
}
}
for(int i=0;i<m;i++)
{for(int j=0;j<n;j++)
cout<<a[i][j]<<" ";
cout<<endl;}
cout<<max_count;
}
And this is the input test case for which it is failing
8
9
0 1 0 0 0 0 1 1 0
1 1 0 0 1 0 0 0 1
0 0 0 0 1 0 1 0 0
0 1 1 1 0 1 0 1 1
0 1 1 1 0 0 1 1 0
0 1 0 1 1 0 1 1 0
0 1 0 0 1 1 0 1 1
1 0 1 1 1 1 0 0 0
And this is output given by code
0 2 0 0 0 0 2 2 0
2 2 0 0 3 0 0 0 1
0 0 0 0 3 0 3 0 0
0 3 3 3 0 3 0 3 1
0 3 3 3 0 0 3 3 0
0 3 0 3 3 0 3 3 0
0 3 0 0 3 3 0 3 1
3 0 3 3 3 3 0 0 0
27
But the output should be 29, for [1,8] [3,8] and [6,8] it is not changing.What must be the problem in the code.
Looks like a typo here:
floodFill(a,i,j,2+i,m,m);
Should be:
floodFill(a,i,j,2+i,m,n);
Unless your matrix is square. It might be worthwhile to abstract the matrix into an object that knows its own dimensions (see here). Then you can pass fewer parameters everywhere.

Which row has the most 1s in a 0-1 matrix with all 1s "on the left"?

Problem
Each row of an n x n matrix consists of 1's and 0's such that in any row, all 1's come before any 0's. Find row containing most no of 1's in O(n).
Example
1 1 1 1 1 0 <- Contains maximum number of 1s, return index 1
1 1 1 0 0 0
1 0 0 0 0 0
1 1 1 1 0 0
1 1 1 1 0 0
1 1 0 0 0 0
I found this question in my algorithms book. The best I could do took O(n logn) time.
How to do this in O(n)?
Start at 1,1.
If the cell contains 1, you're on the longest row so far; write it down and go right.
If the cell contains 0, go down.
If the cell is out of bounds, you're done.
You can do it in O(N) as follows:
Start at A[i][j] with i=j=0.
1, keep moving to the right by doing j++
A[i][j] =
0, move down to the next row by doing i++
When you reach the last row or the last column, the value of j will be the answer.
Pseudo code:
Let R be number of rows
Let C be number of columns
Let i = 0
Let j = 0
Let max1Row = 0
while ( i<R && j<C )
if ( matrix[i][j] == 1 )
j++
max1Row = i
else
i++
end-while
print "Max 1's = j"
print "Row number with max 1's = max1Row"
Start with the first row. Keep the row R that has the most numbers of 1s and the index i of the last 1 of R. in each iteration compare the current row with the row R on the index i. if the current row has a 0 on position i, the row R is still the answer.
Otherwise, return the index of the current row. Now we just have to find the last 1 of the current row. Iterate from index i up to the last 1 of the current row, set R to this row and i to this new index.
i
|
v
R-> 1 1 1 1 1 0
|
v 1 1 1 0 0 0 (Compare ith index of this row)
1 0 0 0 0 0 Repeat
1 1 1 1 0 0 "
1 1 1 1 0 0 "
1 1 0 0 0 0 "
Some C code to do this.
int n = 6;
int maxones = 0, maxrow = -1, row = 0, col = 0;
while(row < n) {
while(col < n && matrix[row][col] == 1) col++;
if(col == n) return row;
if(col > maxones){
maxrow = row;
maxones = col;
}
row++;
}
int [] getMax1withRow(int [][] matrix){
int [] result=new int[2];
int rows=matrix.length;
int cols=matrix[0].length;
int i=0, j=0;
int max_row=0;// This will show row with maximum 1. Intialing pointing to 0th row.
int max_one=0;// max one
while(i< rows){
while(matrix[i][j]==1){
j++;
}
if(j==n){
result[0]=n;
result[1]=i;
return result;
}
if(j>max_one){
max_one=j;
max_row=i;
}
j=0;// Again start from the first column
i++;// increase row number
}
result[0]=max_one;
result[1]=max_row;
return result;
}
Time complexity => O(row+col), In worse case If every row has n-1 one except last row which have n 1s then we have be travel till last row.

Resources