Sunday, July 22, 2012

Given an integer n , you have to print all the ways in which n can be represented as sum of positive integers


#define ARR_SIZE 100
#include<stdio.h>


void printArray(int arr[], int arr_size)
{
int i;
for (i = 0; i < arr_size; i++)
printf("%d ", arr[i]);
printf("\n");
}


/* The function prints all combinations of numbers 1, 2, ...n
that sum up to n. i is used in recursion keep track of index in arr[] where next
element is to be added. Initital value of i must be passed as 0 */
void printCompositions(int n,int m ,int i)
{

/* array must be static as we want to keep track
of values stored in arr[] using current calls of
printCompositions() in function call stack*/
static int arr[ARR_SIZE];

if (n == 0)
{
printArray(arr, i);
}
else if(n > 0)
{
int k;
for (k = 1; k <= m; k++)
{
arr[i]= k;
printCompositions(n-k,m, i+1);
}
}
}


/* Driver function to test above functions */
int main()
{
int n = 5;
printf("Differnt compositions formed by 1, 2 , 3 , 4 and 5  %d are\n", n);
printCompositions(n,n, 0);
getchar();
return 0;
}

Time Complexity O(n^m) Exponential
Space Complexity O(m)
Run Here http://ideone.com/clone/ETZTv

Thursday, July 12, 2012

find the number of maximal squares that can be formed. A square is formed by grouping adjacent cells containing 1. A maximal square is one that is not completely contained within another square. Maximal squares that overlap partially are to be counted separately


Given a matrix of order M x N containing 1.s and 0's, you have to find the number of maximal squares that can be formed. A square is formed by grouping adjacent cells containing 1. A maximal square is one that is not completely contained within another square. Maximal squares that overlap partially are to be counted separately. Unit squares (length of side = 1) should be also counted.
Note that squares are filled, i.e. they cannot contain 0.s.

Number of maximal square: 6
Input specification:
The first line consists of integers M and N, the number of rows and columns of the matrix.
0 < M and N <=40
Next M lines contain N characters from the set {0, 1}.
Output specification:
An integer representing the number of maximal squares that can be formed followed by a newline.
Sample Input and Output:

Input:
4 5
11001
11110
11011
11001

Output:
9

Input:
2 2
10
11

Output:
3

Source: Heard From user Bhavesh