Friday, June 10, 2011

Given a binary matrix of N X N of integers , you need to return only unique rows of binary arrays

eg:
0 1 0 0 1
1 0 1 1 0
0 1 0 0 1
1 1 1 0 0
ans:
0 1 0 0 1
1 0 1 1 0
1 1 1 0 0

Data Structure Used: 2 D Array, Hashing


Algorithm:
Find the value of each row, as in 2^(n-1)*a[0][i]+2^(n-2)*a[1][i]+...+2^(0)*a[n][i]
then compare values and write rows which have difft values (think each row as binary representation of number then we just have to convert each row to decimal representation of number)



Working Code:

#include
#include
#define N 5
int main()
{
int a[N]={0,0,0,0,0},b[N]={-1,-1,-1,-1,-1},p,i,j;
int A[][N] = {
{1,1,0,0,1},
{1,1,0,0,1},
{1,0,0,0,1},
{1,1,0,0,1},
{1,0,0,0,0}
};


for(i=0;i=0;j--)
{
if(A[i][j] == 1)
{
a[i] += pow(2,(N-1)-(j));}
}
}
}

for(i=0;i {
j=a[i] % N;
p=0;
while(b[j] != -1)
{
if(b[j] != a[i])
j = (j+1)%N;
else
{
p=1;
break;
}
}

if(p!=1)
{
for(p=0;p printf("%d ",A[i][p]);

b[j] = a[i];
printf("\n");
}
}

return 0;
}


Time Complexity O(N^2)
Space Complexity O(1)
Auxiliary Space O(N)
Run Here http://ideone.com/clpST

No comments :