Skip to content

Commit 4a15361

Browse files
committed
Added new problems
1 parent 5d5aa35 commit 4a15361

File tree

16 files changed

+849
-0
lines changed

16 files changed

+849
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
void topologicalSortUtil(int v, int visited[], int *stack, int *top, int graph[][100], int vertices) {
5+
visited[v] = 1;
6+
7+
for (int i = 0; i < vertices; i++) {
8+
if (graph[v][i] && !visited[i]) {
9+
topologicalSortUtil(i, visited, stack, top, graph, vertices);
10+
}
11+
}
12+
13+
stack[++(*top)] = v;
14+
}
15+
16+
void topologicalSort(int graph[][100], int vertices) {
17+
int visited[vertices];
18+
int stack[vertices];
19+
int top = -1;
20+
21+
for (int i = 0; i < vertices; i++) {
22+
visited[i] = 0;
23+
}
24+
25+
for (int i = 0; i < vertices; i++) {
26+
if (!visited[i]) {
27+
topologicalSortUtil(i, visited, stack, &top, graph, vertices);
28+
}
29+
}
30+
31+
printf("Topological Sort: ");
32+
while (top >= 0) {
33+
printf("%d ", stack[top--]);
34+
}
35+
printf("\n");
36+
}
37+
38+
int main() {
39+
int vertices, edges;
40+
printf("Enter the number of vertices and edges: ");
41+
scanf("%d %d", &vertices, &edges);
42+
43+
int graph[100][100] = {0};
44+
printf("Enter the edges (u -> v):\n");
45+
for (int i = 0; i < edges; i++) {
46+
int u, v;
47+
scanf("%d %d", &u, &v);
48+
graph[u][v] = 1;
49+
}
50+
51+
topologicalSort(graph, vertices);
52+
53+
return 0;
54+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <stack>
4+
using namespace std;
5+
6+
// Recursive DFS function to process a vertex and its neighbors
7+
void dfs(int v, const vector<vector<int>> &graph, vector<bool> &visited, stack<int> &order) {
8+
visited[v] = true;
9+
for (int neighbor : graph[v]) {
10+
if (!visited[neighbor]) {
11+
dfs(neighbor, graph, visited, order);
12+
}
13+
}
14+
// Push vertex onto stack after all its neighbors are processed
15+
order.push(v);
16+
}
17+
18+
int main() {
19+
int vertices, edges;
20+
cout << "Enter the number of vertices: ";
21+
cin >> vertices;
22+
cout << "Enter the number of edges: ";
23+
cin >> edges;
24+
25+
// Initialize graph as an adjacency list (0-indexed vertices)
26+
vector<vector<int>> graph(vertices);
27+
cout << "Enter each edge (source destination):" << endl;
28+
for (int i = 0; i < edges; i++) {
29+
int u, v;
30+
cin >> u >> v;
31+
// For a directed graph, add an edge from u to v
32+
graph[u].push_back(v);
33+
}
34+
35+
// To keep track of visited vertices
36+
vector<bool> visited(vertices, false);
37+
stack<int> order;
38+
39+
// Perform DFS for each vertex that hasn't been visited
40+
for (int i = 0; i < vertices; i++) {
41+
if (!visited[i]) {
42+
dfs(i, graph, visited, order);
43+
}
44+
}
45+
46+
// Output the topologically sorted order by popping from the stack
47+
cout << "Topological Order: ";
48+
while (!order.empty()) {
49+
cout << order.top() << " ";
50+
order.pop();
51+
}
52+
cout << endl;
53+
54+
return 0;
55+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import java.util.*;
2+
3+
public class TopologicalSort {
4+
static void topologicalSortUtil(int v, boolean[] visited, Stack<Integer> stack, List<List<Integer>> graph) {
5+
visited[v] = true;
6+
7+
for (int neighbor : graph.get(v)) {
8+
if (!visited[neighbor]) {
9+
topologicalSortUtil(neighbor, visited, stack, graph);
10+
}
11+
}
12+
13+
stack.push(v);
14+
}
15+
16+
static void topologicalSort(List<List<Integer>> graph, int vertices) {
17+
boolean[] visited = new boolean[vertices];
18+
Stack<Integer> stack = new Stack<>();
19+
20+
for (int i = 0; i < vertices; i++) {
21+
if (!visited[i]) {
22+
topologicalSortUtil(i, visited, stack, graph);
23+
}
24+
}
25+
26+
System.out.print("Topological Sort: ");
27+
while (!stack.isEmpty()) {
28+
System.out.print(stack.pop() + " ");
29+
}
30+
System.out.println();
31+
}
32+
33+
public static void main(String[] args) {
34+
Scanner scanner = new Scanner(System.in);
35+
System.out.print("Enter the number of vertices and edges: ");
36+
int vertices = scanner.nextInt();
37+
int edges = scanner.nextInt();
38+
39+
List<List<Integer>> graph = new ArrayList<>();
40+
for (int i = 0; i < vertices; i++) {
41+
graph.add(new ArrayList<>());
42+
}
43+
44+
System.out.println("Enter the edges (u -> v):");
45+
for (int i = 0; i < edges; i++) {
46+
int u = scanner.nextInt();
47+
int v = scanner.nextInt();
48+
graph.get(u).add(v);
49+
}
50+
51+
topologicalSort(graph, vertices);
52+
}
53+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
def dfs(v, graph, visited, stack):
2+
"""Recursive DFS that marks visited nodes and appends vertices to stack."""
3+
visited[v] = True
4+
for neighbor in graph[v]:
5+
if not visited[neighbor]:
6+
dfs(neighbor, graph, visited, stack)
7+
stack.append(v)
8+
9+
def topological_sort(graph, vertices):
10+
"""Returns a list of vertices in topologically sorted order."""
11+
visited = [False] * vertices
12+
stack = []
13+
for i in range(vertices):
14+
if not visited[i]:
15+
dfs(i, graph, visited, stack)
16+
# Reverse stack to get the correct topological order.
17+
return stack[::-1]
18+
19+
def main():
20+
vertices = int(input("Enter the number of vertices: "))
21+
edges = int(input("Enter the number of edges: "))
22+
23+
# Initialize the graph as a list of lists
24+
graph = [[] for _ in range(vertices)]
25+
print("Enter each edge (source destination) separated by space:")
26+
for _ in range(edges):
27+
u, v = map(int, input().split())
28+
graph[u].append(v) # Directed edge from u to v
29+
30+
order = topological_sort(graph, vertices)
31+
print("Topological Order:", " ".join(map(str, order)))
32+
33+
if __name__ == "__main__":
34+
main()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
int detectCycleUtil(int v, int visited[], int recStack[], int graph[][100], int vertices) {
5+
visited[v] = 1;
6+
recStack[v] = 1;
7+
8+
for (int i = 0; i < vertices; i++) {
9+
if (graph[v][i]) {
10+
if (!visited[i] && detectCycleUtil(i, visited, recStack, graph, vertices)) {
11+
return 1;
12+
} else if (recStack[i]) {
13+
return 1;
14+
}
15+
}
16+
}
17+
18+
recStack[v] = 0;
19+
return 0;
20+
}
21+
22+
int detectCycle(int graph[][100], int vertices) {
23+
int visited[vertices];
24+
int recStack[vertices];
25+
26+
for (int i = 0; i < vertices; i++) {
27+
visited[i] = 0;
28+
recStack[i] = 0;
29+
}
30+
31+
for (int i = 0; i < vertices; i++) {
32+
if (!visited[i] && detectCycleUtil(i, visited, recStack, graph, vertices)) {
33+
return 1;
34+
}
35+
}
36+
return 0;
37+
}
38+
39+
int main() {
40+
int vertices, edges;
41+
printf("Enter the number of vertices and edges: ");
42+
scanf("%d %d", &vertices, &edges);
43+
44+
int graph[100][100] = {0};
45+
printf("Enter the edges (u -> v):\n");
46+
for (int i = 0; i < edges; i++) {
47+
int u, v;
48+
scanf("%d %d", &u, &v);
49+
graph[u][v] = 1;
50+
}
51+
52+
if (detectCycle(graph, vertices)) {
53+
printf("Cycle detected in the graph.\n");
54+
} else {
55+
printf("No cycle detected in the graph.\n");
56+
}
57+
58+
return 0;
59+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
#include <iostream>
2+
#include <vector>
3+
using namespace std;
4+
5+
// DFS function to detect cycle in a directed graph
6+
bool dfsCycle(int v, const vector<vector<int>>& graph, vector<bool>& visited, vector<bool>& recStack) {
7+
visited[v] = true;
8+
recStack[v] = true;
9+
10+
// Explore all neighbors
11+
for (int neighbor : graph[v]) {
12+
// If neighbor is not visited, do DFS on it
13+
if (!visited[neighbor]) {
14+
if (dfsCycle(neighbor, graph, visited, recStack))
15+
return true;
16+
}
17+
// If neighbor is in the recursion stack, cycle detected
18+
else if (recStack[neighbor]) {
19+
return true;
20+
}
21+
}
22+
23+
// Remove vertex from recursion stack before returning
24+
recStack[v] = false;
25+
return false;
26+
}
27+
28+
// Function to detect cycle in the entire graph
29+
bool detectCycle(const vector<vector<int>>& graph, int V) {
30+
vector<bool> visited(V, false);
31+
vector<bool> recStack(V, false);
32+
33+
for (int i = 0; i < V; i++) {
34+
if (!visited[i]) {
35+
if (dfsCycle(i, graph, visited, recStack))
36+
return true;
37+
}
38+
}
39+
return false;
40+
}
41+
42+
int main() {
43+
int V, E;
44+
cout << "Enter the number of vertices: ";
45+
cin >> V;
46+
cout << "Enter the number of edges: ";
47+
cin >> E;
48+
49+
// Initialize graph as an adjacency list (0-indexed vertices)
50+
vector<vector<int>> graph(V);
51+
cout << "Enter each edge (u v) [directed edge from u to v]:" << endl;
52+
for (int i = 0; i < E; i++) {
53+
int u, v;
54+
cin >> u >> v;
55+
graph[u].push_back(v);
56+
}
57+
58+
if (detectCycle(graph, V))
59+
cout << "Cycle detected in the graph." << endl;
60+
else
61+
cout << "No cycle detected in the graph." << endl;
62+
63+
return 0;
64+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import java.util.*;
2+
3+
public class CycleDetectionDirectedGraph {
4+
static boolean detectCycleUtil(int v, boolean[] visited, boolean[] recStack, List<List<Integer>> graph) {
5+
visited[v] = true;
6+
recStack[v] = true;
7+
8+
for (int neighbor : graph.get(v)) {
9+
if (!visited[neighbor] && detectCycleUtil(neighbor, visited, recStack, graph)) {
10+
return true;
11+
} else if (recStack[neighbor]) {
12+
return true;
13+
}
14+
}
15+
16+
recStack[v] = false;
17+
return false;
18+
}
19+
20+
static boolean detectCycle(List<List<Integer>> graph, int vertices) {
21+
boolean[] visited = new boolean[vertices];
22+
boolean[] recStack = new boolean[vertices];
23+
24+
for (int i = 0; i < vertices; i++) {
25+
if (!visited[i] && detectCycleUtil(i, visited, recStack, graph)) {
26+
return true;
27+
}
28+
}
29+
30+
return false;
31+
}
32+
33+
public static void main(String[] args) {
34+
Scanner scanner = new Scanner(System.in);
35+
System.out.print("Enter the number of vertices and edges: ");
36+
int vertices = scanner.nextInt();
37+
int edges = scanner.nextInt();
38+
39+
List<List<Integer>> graph = new ArrayList<>();
40+
for (int i = 0; i < vertices; i++) {
41+
graph.add(new ArrayList<>());
42+
}
43+
44+
System.out.println("Enter the edges (u -> v):");
45+
for (int i = 0; i < edges; i++) {
46+
int u = scanner.nextInt();
47+
int v = scanner.nextInt();
48+
graph.get(u).add(v);
49+
}
50+
51+
if (detectCycle(graph, vertices)) {
52+
System.out.println("Cycle detected in the graph.");
53+
} else {
54+
System.out.println("No cycle detected in the graph.");
55+
}
56+
57+
scanner.close();
58+
}
59+
}

0 commit comments

Comments
 (0)