# Reconstruct a 2-Row Binary Matrix in C++

Suppose we have the following details of a matrix with n columns and 2 rows −

• Matrix elements will be either 0 or 1
• Sum of elements of the 0-th(upper) row is given as upper.
• Sum of elements of the 1-st(lower) row is given as lower.
• Sum of elements in the i-th column(0-indexed) is colsum[i], where colsum is given as an integer array with length n.

The task is to reconstruct the matrix with upper, lower and colsum. We have to find it as a 2D integer array. If there are more than one valid solution, any of them will be accepted. If there is no valid solution, return an empty 2D array. So if the input is like upper = 2, lower = 3 and colsum is [1,1,1], then output will be [[1,1,0],[0,0,1]]

To solve this, we will follow these steps −

• set flag := true, n := size of c, make one array ans of order 2 * n
• for i in range 0 to n
• if c[i] = 2, then
• decrease u and l by 1
• if u < 0 or l < 0, then flag := false
• put ans[0, i] = 1 and ans[1, i] = 1
• else if c[i] = 1, then
• if u > l, then decrease u by 1, ans[0, i] := 1
• otherwise when u < l, then decrease l by 1 ans[1, i] := 1
• otherwise when c[i] = 1
• if u > 0, then decrease u by 1 and ans[0, i] := 1
• otherwise l > 0, then decrease l by 1 and ans[1, i] := 1
• otherwise set flag := false
• otherwise c[i] = 0
• if c[i] > 0, then set flag := false
• otherwise set flag := false
• if flag is false or u is not 0 or l is not 0, then return empty
• return ans

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto> > v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] << ", ";
}
cout << "],";
}
cout << "]"<<endl;
}
class Solution {
public:
vector<vector<int>> reconstructMatrix(int u, int l, vector<int>& c) {
bool flag = true;
int n = c.size();
vector < vector <int> > ans(2, vector <int> (n));
for(int i = 0; i < n; i++){
if(c[i] == 2){
u--;
l--;
if(u<0 || l<0)flag = false;
ans[i] = 1;
ans[i] = 1;
}else if(c[i] == 1){
if(u>l){
u--;
ans[i] = 1;
}else if(u<l){
l--;
ans[i] = 1;
}else{
if(u>0){
u--;
ans[i] = 1;
}else if(l > 0){
l--;
ans[i] = 1;
}else
flag = false;
}
}else if(c[i] == 0){
if(c[i]>0)flag = false;
}else{
flag = false;
}
}
if(!flag || u!=0 ||l!=0 )return {};
return ans;
}
};
main(){
vector<int> v = {1,1,1};
Solution ob;
print_vector(ob.reconstructMatrix(2,1,v));
}

## Input

2
1
[1,1,1]

## Output

[[1, 1, 0, ],[0, 0, 1, ],]

Updated on: 02-May-2020

117 Views 