0% found this document useful (0 votes)
46 views24 pages

Id - 466

The document contains code submissions for various lab assignments. It includes code for sieve of Eratosthenes, matrix chain multiplication, number of moves to change one number to another, checking if a number can be formed by chunks of 3 or 7, depth first search on a graph, breadth first search on a graph, checking if a graph is bipartite, finding connected components in a graph, Prim's minimum spanning tree algorithm, and Kruskal's minimum spanning tree algorithm. The code submissions are for assignments 07, 08, 09 and 10.

Uploaded by

Md Tariful Islam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views24 pages

Id - 466

The document contains code submissions for various lab assignments. It includes code for sieve of Eratosthenes, matrix chain multiplication, number of moves to change one number to another, checking if a number can be formed by chunks of 3 or 7, depth first search on a graph, breadth first search on a graph, checking if a graph is bipartite, finding connected components in a graph, Prim's minimum spanning tree algorithm, and Kruskal's minimum spanning tree algorithm. The code submissions are for assignments 07, 08, 09 and 10.

Uploaded by

Md Tariful Islam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

LAB REPORT : 07, 08, 09,10

Submitted By :

Md. Faizer Islam


ID : 21225103466
Intake : 49
Sec : 10

Submitted To

Faria Binte Kader


Lecturer
Dept. of CSE
BUBT
LAB : 07 (A)

Code :

#include <bits/stdc++.h>
#include <vector>

using namespace std;

vector<int> sieveOfEratosthenes(int N)
{
vector<bool> isPrime(N + 1, true);
isPrime[0] = isPrime[1] = false;

for (int i = 2; i * i <= N; i++)


{
if (isPrime[i])
{
for (int j = i * i; j <= N; j += i)
{
isPrime[j] = false;
}
}
}

vector<int> primes;
for (int i = 2; i <= N; i++)
{
if (isPrime[i])
{
primes.push_back(i);
}
}
return primes;
}

int main()
{
int N;
cin >> N;

vector<int> primes = sieveOfEratosthenes(N);

for (int prime : primes)


{
cout << prime << " ";
}
cout << endl;

return 0;
}

OUTPUT :

LAB : 07 (B)

Code :

#include <bits/stdc++.h>
#include <climits>
#include <vector>

using namespace std;

int matrix_chain_multiplication(const vector<int>& dimensions)


{
int n = dimensions.size() - 1;
vector<vector<int>> dp(n, vector<int>(n, 0));

for (int length = 2; length <= n; ++length)


{
for (int i = 0; i <= n - length; ++i)
{
int j = i + length - 1;
dp[i][j] = INT_MAX;
for (int k = i; k < j; ++k)
{
int cost = dp[i][k] + dp[k + 1][j] + dimensions[i] * dimensions[k + 1] *
dimensions[j + 1];
dp[i][j] = min(dp[i][j], cost);
}
}
}

return dp[0][n - 1];


}

int main()
{
// Example
int N = 4;
vector<int>dimensions = {1, 2, 3 ,4};
int min_cost = matrix_chain_multiplication(dimensions);

cout << min_cost << endl;

return 0;
}

OUTPUT :
LAB : 07 (C)

Code :

#include <bits/stdc++.h>
#include <algorithm>

using namespace std;

int main() {
int n;
cin >> n;

string original, target;


cin >> original >> target;

int result = 0;
for (int i = 0; i < n; i++) {
int originalDigit = original[i] - '0';
int targetDigit = target[i] - '0';

int diff = (targetDigit - originalDigit + 10) % 10;


int moves = min(diff, 10 - diff);
result += moves;
}

cout << result << endl;

return 0;
}

OUTPUT :
LAB : 07 (D)

Code :

#include <iostream>

using namespace std;

bool buy(int x) {

if (x % 3 == 0) {
return true;
}

if (x % 7 == 0) {
return true;
}

for (int i = 1; i <= x / 7; i++) {


int remainingChunks = x - 7 * i;
if (remainingChunks % 3 == 0) {
return true;
}
}

return false;
}

int main() {
int n;
cin >> n;

while (n--) {
int x;
cin >> x;

if (buy(x)) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}

return 0;
}

OUTPUT :

LAB : 08 (A)

Code :

#include <bits/stdc++.h>
#include <vector>
#include <stack>

using namespace std;

void dfs(vector<vector<int>>& graph, int startNode) {


int numVertices = graph.size();
vector<bool> visited(numVertices, false);
stack<int> nodeStack;
visited[startNode] = true;
nodeStack.push(startNode);

while (!nodeStack.empty()) {
int current = nodeStack.top();
cout << current << " ";
nodeStack.pop();

for (int neighbor : graph[current]) {


if (!visited[neighbor]) {
visited[neighbor] = true;
nodeStack.push(neighbor);
}
}
}
}

int main() {
int numVertices, numEdges;
cin >> numVertices >> numEdges;

vector<vector<int>> graph(numVertices);

for (int i = 0; i < numEdges; i++) {


int u, v;
cin >> u >> v;
graph[u].push_back(v);
}

int startNode;
cin >> startNode;

cout << "DFS Order: ";


dfs(graph, startNode);
cout << endl;

return 0;
}
LAB : 08 (B)

Code :

#include <bits/stdc++.h>
#include <vector>
#include <queue>

using namespace std;

void bfs(vector<vector<int>>& graph, int startNode) {


int numVertices = graph.size();
vector<bool> visited(numVertices, false);
queue<int> nodeQueue;

visited[startNode] = true;
nodeQueue.push(startNode);

while (!nodeQueue.empty()) {
int current = nodeQueue.front();
cout << current << " ";
nodeQueue.pop();

for (int neighbor : graph[current]) {


if (!visited[neighbor]) {
visited[neighbor] = true;
nodeQueue.push(neighbor);
}
}
}
}

int main() {
int numVertices, numEdges;
cin >> numVertices >> numEdges;

vector<vector<int>> graph(numVertices);

for (int i = 0; i < numEdges; i++) {


int u, v;
cin >> u >> v;
graph[u].push_back(v);
}
int startNode;
cin >> startNode;

cout << "BFS Order: ";


bfs(graph, startNode);
cout << endl;

return 0;
}

LAB : 08 (C)

Code :

#include <bits/stdc++.h>

using namespace std;


#define V 4
bool colorGraph(int G[][V],int color[],int pos, int c){

if(color[pos] != -1 && color[pos] !=c)


return false;

color[pos] = c;
bool ans = true;
for(int i=0;i<V;i++){
if(G[pos][i]){
if(color[i] == -1)
ans &= colorGraph(G,color,i,1-c);

if(color[i] !=-1 && color[i] != 1-c)


return false;
}
if (!ans)
return false;
}
return true;
}

bool isBipartite(int G[][V]){


int color[V];
for(int i=0;i<V;i++)
color[i] = -1;

int pos = 0;
return colorGraph(G,color,pos,1);

int main()
{
int G[][V] = {{0, 1, 0, 1},
{1, 0, 1, 0},
{0, 1, 0, 1},
{1, 0, 1, 0}
};

isBipartite(G) ? cout<< "Yes" : cout << "No";


return 0;
}

LAB : 08 (D)

Code :

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

const int MAX_N = 100;

bool isSafe(int i, int j, int n, char mat[MAX_N][MAX_N]) {


return (i >= 0 && i < n && j >= 0 && j < n && mat[i][j] == '1');
}

void DFS(int i, int j, int n, char mat[MAX_N][MAX_N], bool visited[MAX_N][MAX_N]) {


visited[i][j] = true;

for (int di = -1; di <= 1; ++di) {


for (int dj = -1; dj <= 1; ++dj) {
if (di == 0 && dj == 0) continue;

int ni = i + di;
int nj = j + dj;

if (isSafe(ni, nj, n, mat) && !visited[ni][nj]) {


DFS(ni, nj, n, mat, visited);
}
}
}
}

int countConnectedComponents(char mat[MAX_N][MAX_N], int n) {


bool visited[MAX_N][MAX_N];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
visited[i][j] = false;
}
}

int count = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (mat[i][j] == '1' && !visited[i][j]) {
DFS(i, j, n, mat, visited);
count++;
}
}
}

return count;
}

int main() {
int n;
cin >> n;

char mat[MAX_N][MAX_N];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cin >> mat[i][j];
}
}

int count = countConnectedComponents(mat, n);


cout << count << endl;

return 0;
}

OUTPUT :

LAB : 09 (A)

Code :

#include <iostream>
#include <vector>
#include <climits>

using namespace std;


const int MAX = 100;

int primMST(int graph[MAX][MAX], int V) {


vector<int> key(V, INT_MAX);
vector<bool> mstSet(V, false);

key[0] = 0;

int cost = 0;

for (int count = 0; count < V - 1; ++count) {


int u = -1;
for (int v = 0; v < V; ++v) {
if (!mstSet[v] && (u == -1 || key[v] < key[u])) {
u = v;
}
}

mstSet[u] = true;

for (int v = 0; v < V; ++v) {


if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v]) {
key[v] = graph[u][v];
}
}
}

for (int v = 1; v < V; ++v) {


cost += key[v];
}

return cost;
}

int main() {
int V, E;
cin >> V >> E;

int graph[MAX][MAX] = {0};

for (int i = 0; i < E; ++i) {


int u, v, weight;
cin >> u >> v >> weight;
graph[u][v] = graph[v][u] = weight;
}
int minCost = primMST(graph, V);
cout << minCost << endl;

return 0;
}

OUTPUT :

LAB : 09 (B)

Code :

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct Edge {
int u, v, weight;
};

bool compareEdges(const Edge& a, const Edge& b) {


return a.weight < b.weight;
}
int findParent(int v, vector<int>& parent) {
if (parent[v] == -1)
return v;
return findParent(parent[v], parent);
}

void unionSets(int x, int y, vector<int>& parent, vector<int>& rank) {


int rootX = findParent(x, parent);
int rootY = findParent(y, parent);

if (rootX != rootY) {
if (rank[rootX] < rank[rootY])
parent[rootX] = rootY;
else if (rank[rootX] > rank[rootY])
parent[rootY] = rootX;
else {
parent[rootX] = rootY;
rank[rootY]++;
}
}
}

void kruskalMST(vector<Edge>& edges, int V) {


sort(edges.begin(), edges.end(), compareEdges);

vector<int> parent(V, -1);


vector<int> rank(V, 0);

int mstWeight = 0;
for (const Edge& edge : edges) {
int rootU = findParent(edge.u, parent);
int rootV = findParent(edge.v, parent);

if (rootU != rootV) {
cout << edge.u << " - " << edge.v << " Weight: " << edge.weight << endl;
mstWeight += edge.weight;
unionSets(rootU, rootV, parent, rank);
}
}

cout << "Total MST Weight: " << mstWeight << endl;
}

int main() {
int V, E;
cin >> V >> E;
vector<Edge> edges(E);
for (int i = 0; i < E; ++i) {
cin >> edges[i].u >> edges[i].v >> edges[i].weight;
}

kruskalMST(edges, V);

return 0;
}

OUTPUT :

LAB : 09 (C)

Code :

#include <bits/stdc++.h>
#include <vector>
#include <algorithm>

using namespace std;


struct Edge {
int u, v, weight;
};

bool compareEdges(const Edge& a, const Edge& b) {


return a.weight < b.weight;
}

int findParent(int v, vector<int>& parent) {


if (parent[v] == -1)
return v;
return findParent(parent[v], parent);
}

bool isCycle(int u, int v, vector<int>& parent) {


int rootU = findParent(u, parent);
int rootV = findParent(v, parent);

return rootU == rootV;


}

void unionSets(int x, int y, vector<int>& parent, vector<int>& rank) {


int rootX = findParent(x, parent);
int rootY = findParent(y, parent);

if (rootX != rootY) {
if (rank[rootX] < rank[rootY])
parent[rootX] = rootY;
else if (rank[rootX] > rank[rootY])
parent[rootY] = rootX;
else {
parent[rootX] = rootY;
rank[rootY]++;
}
}
}

bool hasCycle(vector<Edge>& edges, int V) {


sort(edges.begin(), edges.end(), compareEdges);

vector<int> parent(V, -1);


vector<int> rank(V, 0);

for (const Edge& edge : edges) {


int u = edge.u;
int v = edge.v;
if (isCycle(u, v, parent)) {
return true; // Cycle detected
}

unionSets(u, v, parent, rank);


}

return false;
}

int main() {
int V, E;
cin >> V >> E;

vector<Edge> edges(E);
for (int i = 0; i < E; ++i) {
cin >> edges[i].u >> edges[i].v >> edges[i].weight;
}

if (hasCycle(edges, V)) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}

return 0;
}

LAB : 10 (A)

Code :

#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;

#define INF INT_MAX

class Graph {
public:
int vertices;
vector<vector<pair<int, int>>> adjacencyList;

Graph(int V) : vertices(V), adjacencyList(V) {}

void addEdge(int u, int v, int weight) {


adjacencyList[u].push_back(make_pair(v, weight));
adjacencyList[v].push_back(make_pair(u, weight)); // If the graph is undirected
}

void dijkstra(int source) {


priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
vector<int> distance(vertices, INF);

pq.push(make_pair(0, source));
distance[source] = 0;

while (!pq.empty()) {
int u = pq.top().second;
pq.pop();

for (const auto& neighbor : adjacencyList[u]) {


int v = neighbor.first;
int weight = neighbor.second;

if (distance[u] + weight < distance[v]) {


distance[v] = distance[u] + weight;
pq.push(make_pair(distance[v], v));
}
}
}

cout << "Shortest distances from source " << source << " to all other vertices:\n";
for (int i = 0; i < vertices; ++i) {
cout << "Vertex " << i << ": ";
if (distance[i] == INF)
cout << "INF\n";
else
cout << distance[i] << "\n";
}
}
};

int main() {
int vertices, edges;
cout << "Enter the number of vertices: ";
cin >> vertices;

Graph g(vertices);

cout << "Enter the number of edges: ";


cin >> edges;

cout << "Enter the edges with weights (format: source destination weight):\n";
for (int i = 0; i < edges; ++i) {
int u, v, weight;
cin >> u >> v >> weight;
g.addEdge(u, v, weight);
}

int source;
cout << "Enter the source vertex: ";
cin >> source;

g.dijkstra(source);

return 0;
}
OUTPUT :

LAB : 10 (B)

Code :

#include <bits/stdc++.h>
#include <vector>
#include <climits>

using namespace std;

#define INF INT_MAX

struct Edge {
int src, dest, weight;
};
class Graph {
public:
int vertices, edges;
vector<Edge> edgeList;

Graph(int V, int E) : vertices(V), edges(E) {}

void addEdge(int src, int dest, int weight) {


edgeList.push_back({src, dest, weight});
}

void bellmanFord(int source) {


vector<int> distance(vertices, INF);
distance[source] = 0;

// Relax all edges for (vertices - 1) times


for (int i = 1; i <= vertices - 1; ++i) {
for (const auto& edge : edgeList) {
int u = edge.src;
int v = edge.dest;
int w = edge.weight;

if (distance[u] != INF && distance[u] + w < distance[v]) {


distance[v] = distance[u] + w;
}
}
}

// Check for negative weight cycles


for (const auto& edge : edgeList) {
int u = edge.src;
int v = edge.dest;
int w = edge.weight;

if (distance[u] != INF && distance[u] + w < distance[v]) {


cout << "Graph contains negative weight cycle. Cannot find shortest
paths.\n";
return;
}
}

cout << "Shortest distances from source " << source << " to all other vertices:\n";
for (int i = 0; i < vertices; ++i) {
cout << "Vertex " << i << ": ";
if (distance[i] == INF)
cout << "INF\n";
else
cout << distance[i] << "\n";
}
}
};

int main() {
int vertices, edges;
cout << "Enter the number of vertices: ";
cin >> vertices;

cout << "Enter the number of edges: ";


cin >> edges;

Graph g(vertices, edges);

cout << "Enter the edges with weights (format: source destination weight):\n";
for (int i = 0; i < edges; ++i) {
int u, v, weight;
cin >> u >> v >> weight;
g.addEdge(u, v, weight);
}

int source;
cout << "Enter the source vertex: ";
cin >> source;

g.bellmanFord(source);

return 0;
}

You might also like