-
Notifications
You must be signed in to change notification settings - Fork 1
/
CountMatrix.java
executable file
·73 lines (63 loc) · 1.69 KB
/
CountMatrix.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Java program to find the row
// with maximum number of 1s
import java.io.*;
class CountMatrix {
static int R = 4, C = 4;
// Function to find the index of first index
// of 1 in a boolean array arr[]
static int first(int arr[], int low, int high)
{
int res = -1;
if (high >= low) {
// Get the middle index
// Check if the element at middle index is first 1
while(low <= high){
int mid = low + (high - low) / 2;
if (arr[mid] == 1) {
res=mid;
high=mid-1;
}
// If the element is 0, recur for right side
else if (arr[mid] <1)
low=mid+1;
// If element is not first 1, recur for left side
else
high=mid-1;
}
}
return res;
}
// Function that returns index of row
// with maximum number of 1s.
static int rowWithMax1s(int mat[][]) {
int first_index,max_row_index=Integer.MAX_VALUE;
int max=first(mat[0],0,mat.length-1); //checking for first row
if(max==0) return 0; // if 1 is at 0th index then return the row (as it is the row with max 1s)
for(int i = 1; i < mat.length;i++){
if(max!=-1 && mat[i][max]==1){
first_index=first(mat[i],0,max-1);
System.out.println(first_index);
if(first_index!=-1 && first_index<max){
max=first_index;
max_row_index=i;
}
}
else{
if(max==-1) max=first(mat[i],0,C-1);
System.out.println(max);
max_row_index=Math.min(max_row_index,i);
}
}
return max_row_index;
}
// Driver Code
public static void main(String[] args)
{
int mat[][] = { { 0, 0, 0, 0 },
{ 0, 1, 1, 1 },
{ 1, 1, 1, 1 },
{ 0, 0, 0, 0 } };
System.out.println("Index of row with maximum 1s is "
+ rowWithMax1s(mat));
}
}