0% found this document useful (0 votes)
18 views

Assignment No-3

The document provides code implementations for common graph algorithms and problems: 1) Traveling Salesman Problem using nearest neighbor algorithm, 2) Graph coloring using greedy algorithm, 3) Finding all subsets that sum to a target using backtracking, 4) 0/1 Knapsack problem using dynamic programming, 5) Finding live nodes, E-nodes, and dead nodes in a graph using DFS.
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)
18 views

Assignment No-3

The document provides code implementations for common graph algorithms and problems: 1) Traveling Salesman Problem using nearest neighbor algorithm, 2) Graph coloring using greedy algorithm, 3) Finding all subsets that sum to a target using backtracking, 4) 0/1 Knapsack problem using dynamic programming, 5) Finding live nodes, E-nodes, and dead nodes in a graph using DFS.
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/ 8

1.

Write a Java Program in C/C++/ Java to implement Traveling Salesman Problem


using nearest neighbor algorithm.

import java.util.ArrayList;
import java.util.Arrays;

public class TravelingSalesman {

// Function to find the nearest unvisited neighbor


public static int findNearestNeighbor(int currentCity, boolean[] visited, int[][] distances) {
int nearestCity = -1;
int minDistance = Integer.MAX_VALUE;

for (int city = 0; city < distances.length; city++) {


if (!visited[city] && distances[currentCity][city] < minDistance) {
nearestCity = city;
minDistance = distances[currentCity][city];
}
}

return nearestCity;
}

// Function to calculate the TSP tour using the nearest neighbor algorithm
public static ArrayList<Integer> nearestNeighborTSP(int startCity, int[][] distances) {
int n = distances.length;
boolean[] visited = new boolean[n];
ArrayList<Integer> tour = new ArrayList<>();

int currentCity = startCity;


tour.add(currentCity);
visited[currentCity] = true;

for (int i = 1; i < n; i++) {


int nearestCity = findNearestNeighbor(currentCity, visited, distances);
tour.add(nearestCity);
visited[nearestCity] = true;
currentCity = nearestCity;
}

// Return to the starting city to complete the tour


tour.add(startCity);

return tour;
}

// Function to calculate the total tour distance


public static int calculateTourDistance(ArrayList<Integer> tour, int[][] distances) {
int totalDistance = 0;
for (int i = 0; i < tour.size() - 1; i++) {
int city1 = tour.get(i);
int city2 = tour.get(i + 1);
totalDistance += distances[city1][city2];
}
return totalDistance;
}

public static void main(String[] args) {


// Example distances between cities in a matrix
int[][] distances = {
{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}
};

int startCity = 0; // Start the tour from city 0

ArrayList<Integer> tour = nearestNeighborTSP(startCity, distances);

System.out.println("Tour: " + tour);


int totalDistance = calculateTourDistance(tour, distances);
System.out.println("Total distance of the tour: " + totalDistance);
}
}

2. Write a program in C/C++/ Java a to implement Graph Coloring Algorithm.



import java.util.Arrays;

public class GraphColoring {

// Function to assign colors to vertices using a greedy algorithm


public static int[] graphColoring(int[][] graph, int numColors) {
int numVertices = graph.length;
int[] colors = new int[numVertices];

// Initialize all vertices as uncolored (0 means uncolored)


Arrays.fill(colors, 0);

// Assign colors to each vertex


for (int vertex = 0; vertex < numVertices; vertex++) {
// Find available colors
boolean[] availableColors = new boolean[numColors + 1];
Arrays.fill(availableColors, true);

// Check colors of adjacent vertices and mark them unavailable


for (int neighbor = 0; neighbor < numVertices; neighbor++) {
if (graph[vertex][neighbor] == 1 && colors[neighbor] != 0) {
availableColors[colors[neighbor]] = false;
}
}

// Assign the first available color to the current vertex


for (int color = 1; color <= numColors; color++) {
if (availableColors[color]) {
colors[vertex] = color;
break;
}
}
}

return colors;
}

public static void main(String[] args) {


// Example graph represented as an adjacency matrix
int[][] graph = {
{0, 1, 1, 0, 0, 0},
{1, 0, 1, 1, 0, 0},
{1, 1, 0, 1, 1, 0},
{0, 1, 1, 0, 1, 1},
{0, 0, 1, 1, 0, 1},
{0, 0, 0, 1, 1, 0}
};

int numColors = 3; // Number of colors to use


int[] colors = graphColoring(graph, numColors);

// Output the color assigned to each vertex


System.out.println("Vertex coloring:");
for (int vertex = 0; vertex < colors.length; vertex++) {
System.out.println("Vertex " + vertex + ": Color " + colors[vertex]);
}
}
}

3. Write a program in C/C++/ Java to implement Sum of Subset by Backtracking.



#include <iostream>
#include <vector>

// Function to find all subsets that sum up to a given target using backtracking
void subsetSum(
const std::vector<int>& set,
std::vector<int>& currentSubset,
int currentIndex,
int currentSum,
int targetSum
){
// If the current sum equals the target, print the subset
if (currentSum == targetSum) {
std::cout << "Subset found: ";
for (int num : currentSubset) {
std::cout << num << " ";
}
std::cout << std::endl;
return; // Return to explore other subsets
}

// If the current sum exceeds the target, backtrack


if (currentSum > targetSum || currentIndex >= set.size()) {
return;
}

// Include the current element in the subset


currentSubset.push_back(set[currentIndex]);
subsetSum(set, currentSubset, currentIndex + 1, currentSum + set[currentIndex], targetSum);

// Exclude the current element and move to the next one


currentSubset.pop_back();
subsetSum(set, currentSubset, currentIndex + 1, currentSum, targetSum);
}

int main() {
// Example set of numbers
std::vector<int> set = {3, 34, 4, 12, 5, 2};

int targetSum = 9; // The target sum to find

std::vector<int> currentSubset; // The current subset being explored

std::cout << "Finding subsets with sum " << targetSum << ":\n";
subsetSum(set, currentSubset, 0, 0, targetSum);

return 0;
}

4. Write a program in C/C++/ Java to find out solution for 0/1 knapsack problem.

#include <iostream>
#include <vector>
#include <algorithm> // for std::max

// Function to solve the 0/1 Knapsack problem using dynamic programming


int knapsack(const std::vector<int>& weights, const std::vector<int>& values, int capacity) {
int n = weights.size();
// Create a table to store the maximum value for each capacity from 0 to the given capacity
std::vector<std::vector<int>> dp(n + 1, std::vector<int>(capacity + 1, 0));

// Build the table in a bottom-up manner


for (int i = 1; i <= n; ++i) {
for (int w = 0; w <= capacity; ++w) {
if (weights[i - 1] <= w) {
// If the item can fit in the current capacity
dp[i][w] = std::max(
dp[i - 1][w], // Exclude the item
values[i - 1] + dp[i - 1][w - weights[i - 1]] // Include the item
);
} else {
// If the item can't fit in the current capacity, exclude it
dp[i][w] = dp[i - 1][w];
}
}
}

return dp[n][capacity]; // Return the maximum value that can be obtained


}

int main() {
// Example weights and values of items
std::vector<int> weights = {1, 3, 4, 5};
std::vector<int> values = {1, 4, 5, 7};

int capacity = 7; // Maximum capacity of the knapsack

int maxValue = knapsack(weights, values, capacity);

std::cout << "Maximum value that can be obtained with a capacity of " << capacity << " is " <<
maxValue << "." << std::endl;

return 0;
}

5. Write a program in C/C++/ Java to find out live node, E node and dead node from a
given graph.

#include <iostream>
#include <vector>
#include <stack>
#include <unordered_set>

// Graph representation using adjacency list


class Graph {
public:
Graph(int vertices) : adjList(vertices) {}

void addEdge(int src, int dest) {


adjList[src].push_back(dest);
}

// DFS to find live nodes, E-nodes, and dead nodes


void findNodeStates(int start) {
std::vector<bool> visited(adjList.size(), false);
std::unordered_set<int> liveNodes;
std::unordered_set<int> deadNodes;
std::stack<int> stack;

// Initially, all nodes are live nodes


for (int i = 0; i < adjList.size(); ++i) {
liveNodes.insert(i);
}

// Start DFS from the given node


stack.push(start);

while (!stack.empty()) {
int current = stack.top();
stack.pop();

// If the node has not been visited, it becomes an E-node (expansion)


if (!visited[current]) {
visited[current] = true;
liveNodes.erase(current); // Remove from live nodes
std::cout << "Exploring node " << current << " (E-node)\n";

// Explore all adjacent nodes


for (int neighbor : adjList[current]) {
if (!visited[neighbor]) {
stack.push(neighbor);
}
}

deadNodes.insert(current); // Once explored, it becomes a dead node


}
}

std::cout << "Live nodes: ";


for (int node : liveNodes) {
std::cout << node << " ";
}
std::cout << "\nDead nodes: ";
for (int node : deadNodes) {
std::cout << node << " ";
}
std::cout << std::endl;
}

private:
std::vector<std::vector<int>> adjList; // Adjacency list
};

int main() {
Graph g(6);

// Example graph with 6 nodes and directed edges


g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.addEdge(4, 5);

std::cout << "Finding live nodes, E-nodes, and dead nodes:\n";


g.findNodeStates(0); // Start DFS from node 0

return 0;
}

You might also like