Skip to content

Commit 5b500ec

Browse files
authored
Merge pull request #38 from Arnavthakare19/main
Created Graph algorithms folder
2 parents cd88ceb + fc819d5 commit 5b500ec

10 files changed

+881
-0
lines changed
+92
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
import java.util.*;
2+
3+
public class BellmanFordAlgorithm {
4+
5+
static class Edge {
6+
int src, dest, weight;
7+
8+
Edge(int src, int dest, int weight) {
9+
this.src = src;
10+
this.dest = dest;
11+
this.weight = weight;
12+
}
13+
}
14+
15+
public static void bellmanFord(List<Edge> edges, int V, int start) {
16+
int[] dist = new int[V];
17+
Arrays.fill(dist, Integer.MAX_VALUE);
18+
dist[start] = 0;
19+
20+
for (int i = 0; i < V - 1; i++) {
21+
for (Edge edge : edges) {
22+
int u = edge.src;
23+
int v = edge.dest;
24+
int w = edge.weight;
25+
26+
if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) {
27+
dist[v] = dist[u] + w;
28+
}
29+
}
30+
}
31+
32+
// Check for negative-weight cycles
33+
for (Edge edge : edges) {
34+
int u = edge.src;
35+
int v = edge.dest;
36+
int w = edge.weight;
37+
38+
if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) {
39+
System.out.println("Graph contains a negative-weight cycle.");
40+
return;
41+
}
42+
}
43+
44+
System.out.println("Shortest Distances from Node " + start + ":");
45+
for (int i = 0; i < V; i++) {
46+
System.out.println("Node " + i + ": " + dist[i]);
47+
}
48+
}
49+
50+
public static void main(String[] args) {
51+
int V = 5;
52+
List<Edge> edges = new ArrayList<>();
53+
edges.add(new Edge(0, 1, 4));
54+
edges.add(new Edge(0, 2, 3));
55+
edges.add(new Edge(1, 2, -2));
56+
edges.add(new Edge(1, 3, 2));
57+
edges.add(new Edge(1, 4, 3));
58+
edges.add(new Edge(3, 2, 5));
59+
edges.add(new Edge(3, 1, 1));
60+
edges.add(new Edge(4, 3, -4));
61+
62+
int startNode = 0;
63+
64+
bellmanFord(edges, V, startNode);
65+
}
66+
}
67+
68+
/*
69+
The provided Java program implements the Bellman-Ford algorithm to find the shortest distances from a given starting node to all other nodes in a directed graph. Here's a description of the program:
70+
71+
BellmanFordAlgorithm Class:
72+
73+
This is the main class that contains the bellmanFord method for performing the Bellman-Ford algorithm and the main method to demonstrate its usage.
74+
Edge Class:
75+
76+
The Edge class is a nested class used to represent edges in the graph. Each edge has a source node (src), a destination node (dest), and a weight (weight) associated with it.
77+
bellmanFord Method:
78+
79+
The bellmanFord method takes three parameters: a list of Edge objects representing the graph's edges (edges), the number of vertices (V), and the starting node (start) from which the shortest distances are to be calculated.
80+
It initializes an array dist to store the shortest distances from the starting node to all other nodes. Initially, all distances are set to Integer.MAX_VALUE except for the starting node, which is set to 0.
81+
The method then performs the Bellman-Ford algorithm by iterating over the vertices V - 1 times (where V is the number of vertices). In each iteration, it relaxes the edges by checking if there is a shorter path to a vertex through the current vertex. If a shorter path is found, it updates the distance.
82+
After the main loop, the method checks for the presence of negative-weight cycles by iterating over the edges again. If a shorter path is found, it indicates the existence of a negative-weight cycle in the graph.
83+
Finally, it prints the shortest distances from the starting node to all other nodes.
84+
main Method:
85+
86+
The main method is the entry point of the program.
87+
It creates a graph with 5 vertices and initializes a list of Edge objects (edges) to represent the graph's edges.
88+
Each Edge object in the edges list represents a directed edge with its source, destination, and weight.
89+
It specifies the starting node (startNode) from which to find the shortest distances.
90+
It calls the bellmanFord method with the graph's edges, the number of vertices, and the starting node as arguments to calculate and display the shortest distances.
91+
Overall, this program demonstrates the Bellman-Ford algorithm for finding the shortest distances in a weighted directed graph. It also checks for the presence of negative-weight cycles, which can affect the correctness of the shortest path calculations.
92+
*/
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import java.util.*;
2+
3+
public class DijkstrasAlgorithmMST {
4+
5+
public static void dijkstra(int[][] graph, int start) {
6+
int V = graph.length;
7+
int[] dist = new int[V];
8+
Arrays.fill(dist, Integer.MAX_VALUE);
9+
dist[start] = 0;
10+
11+
boolean[] visited = new boolean[V];
12+
13+
for (int count = 0; count < V - 1; count++) {
14+
int u = minDistance(dist, visited);
15+
visited[u] = true;
16+
17+
for (int v = 0; v < V; v++) {
18+
if (!visited[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE
19+
&& dist[u] + graph[u][v] < dist[v]) {
20+
dist[v] = dist[u] + graph[u][v];
21+
}
22+
}
23+
}
24+
25+
System.out.println("Shortest Distances from Node " + start + ":");
26+
for (int i = 0; i < V; i++) {
27+
System.out.println("Node " + i + ": " + dist[i]);
28+
}
29+
}
30+
31+
public static int minDistance(int[] dist, boolean[] visited) {
32+
int V = dist.length;
33+
int minDist = Integer.MAX_VALUE;
34+
int minIndex = -1;
35+
36+
for (int v = 0; v < V; v++) {
37+
if (!visited[v] && dist[v] < minDist) {
38+
minDist = dist[v];
39+
minIndex = v;
40+
}
41+
}
42+
43+
return minIndex;
44+
}
45+
46+
public static void main(String[] args) {
47+
int[][] graph = {
48+
{0, 4, 0, 0, 0, 0, 0, 8, 0},
49+
{4, 0, 8, 0, 0, 0, 0, 11, 0},
50+
{0, 8, 0, 7, 0, 4, 0, 0, 2},
51+
{0, 0, 7, 0, 9, 14, 0, 0, 0},
52+
{0, 0, 0, 9, 0, 10, 0, 0, 0},
53+
{0, 0, 4, 14, 10, 0, 2, 0, 0},
54+
{0, 0, 0, 0, 0, 2, 0, 1, 6},
55+
{8, 11, 0, 0, 0, 0, 1, 0, 7},
56+
{0, 0, 2, 0, 0, 0, 6, 7, 0}
57+
};
58+
59+
int startNode = 0;
60+
61+
dijkstra(graph, startNode);
62+
}
63+
}
+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import java.util.*;
2+
3+
public class DijkstrasAlgorithmSP {
4+
5+
public static void dijkstra(int[][] graph, int start) {
6+
int V = graph.length;
7+
int[] dist = new int[V];
8+
Arrays.fill(dist, Integer.MAX_VALUE);
9+
dist[start] = 0;
10+
11+
boolean[] visited = new boolean[V];
12+
13+
for (int count = 0; count < V - 1; count++) {
14+
int u = minDistance(dist, visited);
15+
visited[u] = true;
16+
17+
for (int v = 0; v < V; v++) {
18+
if (!visited[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE
19+
&& dist[u] + graph[u][v] < dist[v]) {
20+
dist[v] = dist[u] + graph[u][v];
21+
}
22+
}
23+
}
24+
25+
System.out.println("Shortest Distances from Node " + start + ":");
26+
for (int i = 0; i < V; i++) {
27+
System.out.println("Node " + i + ": " + dist[i]);
28+
}
29+
}
30+
31+
public static int minDistance(int[] dist, boolean[] visited) {
32+
int V = dist.length;
33+
int minDist = Integer.MAX_VALUE;
34+
int minIndex = -1;
35+
36+
for (int v = 0; v < V; v++) {
37+
if (!visited[v] && dist[v] < minDist) {
38+
minDist = dist[v];
39+
minIndex = v;
40+
}
41+
}
42+
43+
return minIndex;
44+
}
45+
46+
public static void main(String[] args) {
47+
int[][] graph = {
48+
{0, 4, 0, 0, 0, 0, 0, 8, 0},
49+
{4, 0, 8, 0, 0, 0, 0, 11, 0},
50+
{0, 8, 0, 7, 0, 4, 0, 0, 2},
51+
{0, 0, 7, 0, 9, 14, 0, 0, 0},
52+
{0, 0, 0, 9, 0, 10, 0, 0, 0},
53+
{0, 0, 4, 14, 10, 0, 2, 0, 0},
54+
{0, 0, 0, 0, 0, 2, 0, 1, 6},
55+
{8, 11, 0, 0, 0, 0, 1, 0, 7},
56+
{0, 0, 2, 0, 0, 0, 6, 7, 0}
57+
};
58+
59+
int startNode = 0;
60+
61+
dijkstra(graph, startNode);
62+
}
63+
}

Graph algorithms/FloodFill.java

+101
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
public class FloodFill {
2+
3+
public static void floodFill(int[][] image, int sr, int sc, int newColor) {
4+
int rows = image.length;
5+
int cols = image[0].length;
6+
int oldColor = image[sr][sc];
7+
8+
if (oldColor != newColor) {
9+
dfs(image, sr, sc, oldColor, newColor, rows, cols);
10+
}
11+
}
12+
13+
public static void dfs(int[][] image, int row, int col, int oldColor, int newColor, int rows, int cols) {
14+
if (row < 0 || row >= rows || col < 0 || col >= cols || image[row][col] != oldColor) {
15+
return;
16+
}
17+
18+
image[row][col] = newColor;
19+
20+
dfs(image, row - 1, col, oldColor, newColor, rows, cols);
21+
dfs(image, row + 1, col, oldColor, newColor, rows, cols);
22+
dfs(image, row, col - 1, oldColor, newColor, rows, cols);
23+
dfs(image, row, col + 1, oldColor, newColor, rows, cols);
24+
}
25+
26+
public static void main(String[] args) {
27+
int[][] image = {
28+
{1, 1, 1},
29+
{1, 1, 0},
30+
{1, 0, 1}
31+
};
32+
33+
int sr = 1, sc = 1, newColor = 2;
34+
35+
floodFill(image, sr, sc, newColor);
36+
37+
System.out.println("Flood-Filled Image:");
38+
for (int[] row : image) {
39+
for (int pixel : row) {
40+
System.out.print(pixel + " ");
41+
}
42+
System.out.println();
43+
}
44+
}
45+
}
46+
47+
48+
49+
50+
// Description of the above code:
51+
52+
// 1. The `FloodFill` class contains three methods: `floodFill`, `dfs`, and `main`.
53+
54+
// 2. `floodFill` method:
55+
// - This method serves as the entry point for the flood fill algorithm.
56+
// - It takes four parameters:
57+
// - `image`: A 2D integer array representing the image where the flood fill should be performed.
58+
// - `sr` and `sc`: The starting row and column coordinates from where the flood fill should begin.
59+
// - `newColor`: The new color that should replace the old color in the connected region.
60+
// - It gets the dimensions of the `image` (number of rows and columns) and stores them in `rows` and `cols`.
61+
// - It retrieves the old color from the `image` at the starting coordinates `(sr, sc)`.
62+
// - If the old color is not equal to the new color, it calls the `dfs` method to perform the flood fill.
63+
64+
// 3. `dfs` method:
65+
// - This is a recursive depth-first search (DFS) function that performs the actual flood fill.
66+
// - It takes six parameters:
67+
// - `image`: The 2D integer array representing the image.
68+
// - `row` and `col`: The current row and column coordinates being processed.
69+
// - `oldColor`: The old color that needs to be replaced.
70+
// - `newColor`: The new color to fill the region with.
71+
// - `rows` and `cols`: The dimensions of the image.
72+
// - It checks if the current coordinates are outside the image boundaries or if the pixel at `(row, col)` does not match the old color. In such cases, it returns, indicating that this branch of the recursion should stop.
73+
// - If the conditions are met, it updates the color at `(row, col)` to the new color.
74+
// - Then, it recursively calls `dfs` for the four neighboring pixels (up, down, left, and right), continuing the flood fill process.
75+
76+
// 4. `main` method:
77+
// - In the `main` method, an example image represented by a 2D array `image` is defined.
78+
// - The starting row (`sr`), starting column (`sc`), and the new color (`newColor`) are specified.
79+
// - The `floodFill` method is called with these parameters to perform the flood fill.
80+
// - Finally, the modified image is printed to the console to display the result.
81+
82+
// The code demonstrates how to use the flood fill algorithm to replace a connected region of pixels with a new color in a 2D image.
83+
84+
/*The provided Java code implements the flood fill algorithm to change the color of a connected region in a 2D image. It starts from a given pixel and recursively fills adjacent pixels of the same original color with a new color. Here's a short description:
85+
86+
The `floodFill` method:
87+
- Takes an image represented as a 2D array, a starting pixel (sr, sc), and a new color.
88+
- Checks if the old color at the starting pixel is different from the new color.
89+
- If they are different, it calls the `dfs` method to perform the flood fill.
90+
91+
The `dfs` method:
92+
- Recursively explores neighboring pixels in four directions (up, down, left, right).
93+
- Changes the color of each visited pixel to the new color.
94+
- Stops when it encounters out-of-bounds pixels or pixels with colors different from the old color.
95+
96+
In the `main` method:
97+
- An example image is provided as a 2D array.
98+
- A starting point (sr, sc) and a new color are specified.
99+
- The `floodFill` method is called to fill the connected region starting from the specified point with the new color.
100+
- The resulting image is printed to the console.*/
101+

0 commit comments

Comments
 (0)