Uploaded by X Dyes

dsafat

advertisement
1. Implement balanced bracket (pair matched) for following two types of brackets
(,), {,} using stack/stacks (B=balanced, and NB=Not Balanced). Your input should
be as below n= 4 (Take input as n)
Algorithm
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
char stack[20];
int top=-1;
void push(char a)
{
top=top+1;
stack[top]=a;
}
char pop()
{
char x=stack[top];
top=top-1;
return x;
}
int main()
{
int n;
printf("Enter number of expressions: ");
scanf("%d",&n);
char a[n][20],t;
printf("the given bracket expressions are:\n");
for(int j=0;j<n;j++)
scanf("%s",&a[j]);
for(int j=0;j<n;j++)
{
bool check=true;
for(int i=0;i<strlen(a[j]);i++)
{
if(a[j][i]=='(' || a[j][i]=='{' || a[j][i]=='[')
{
push(a[j][i]);
}
else if(a[j][i]==')' || a[j][i]=='}' || a[j][i]==']')
{
if(top==-1)
{
check=false;
}
else
{
t=pop();
if(a[j][i]=='(' && (t==']' || t=='}'))
{
check=false;
}
if(a[j][i]=='[' && (t==')' || t=='}'))
{
check=false;
}
if(a[j][i]=='{' && (t==']' || t==')'))
{
check=false;
}
}
}
}
if(top>=0)
{
check=false;
}
if(check==false)
{
printf("NB\n");
}
else
{
printf("B\n");
}
}
}
2. Implement Prims algorithm using C programming using adjacency matrix.
Algorithm:
Code:
#include<stdio.h>
#include<stdbool.h>
#define INF 9999999
#define V 5
int main()
{
int n,x,y,a[V][V];
printf("Enter 5X5 Adjacency Matrix:\n");
for(int i=0;i<V;i++)
for(int j=0;j<V;j++)
scanf("%d",&a[i][j]);
int s[V];
memset(s, false, sizeof(s));
n=0;
s[0]=true;
printf("Edge : Weight\n");
while(n<V-1)
{
int min=INF;
x=0;
y=0;
for (int i=0; i<V; i++)
{
if (s[i])
{
for (int j=0; j<V; j++)
{
if (!s[j] && a[i][j])
{
if (min>a[i][j])
{
min=a[i][j];
x=i;
y=j;
}
}
}
}
}
printf("%d-%d:%d\n", x, y, a[x][y]);
s[y]=true;
n++;
}
return 0;
}
Download