0% found this document useful (0 votes)
3 views1 page

DFS Java

This Java program implements a Depth First Search (DFS) algorithm for an undirected graph. It initializes a graph using an adjacency matrix, allows the user to input the number of vertices and edges, and then performs DFS starting from vertex 0. The program outputs the order of vertices visited during the DFS traversal.

Uploaded by

amanmohammad9410
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views1 page

DFS Java

This Java program implements a Depth First Search (DFS) algorithm for an undirected graph. It initializes a graph using an adjacency matrix, allows the user to input the number of vertices and edges, and then performs DFS starting from vertex 0. The program outputs the order of vertices visited during the DFS traversal.

Uploaded by

amanmohammad9410
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

import [Link].

Scanner;

class DFSGraph { static final int MAX = 10; // Maximum number of vertices
static int[][] adjMatrix = new int[MAX][MAX];
static int[] visited = new int[MAX];
static int vertices; // Function to perform Depth First Search
static void DFS(int vertex)
{ [Link](vertex + " ");
visited[vertex] = 1;
for (int i = 0; i < vertices; i++) {
if (adjMatrix[vertex][i] == 1 && visited[i] == 0) {
DFS(i);
} } }

// Function to initialize graph


static void initializeGraph() {
for (int i = 0; i < MAX; i++) {
visited[i] = 0;
for (int j = 0; j < MAX; j++) {
adjMatrix[i][j] = 0;
}
}
}

// Function to add an edge (Undirected graph)


static void addEdge(int src, int dest) {
adjMatrix[src][dest] = 1;
adjMatrix[dest][src] = 1;
}

// Main method
public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter number of vertices: ");


vertices = [Link]();

[Link]("Enter number of edges: ");


int edges = [Link]();

initializeGraph();

[Link]("Enter edges (source destination):");


for (int i = 0; i < edges; i++) {
int src = [Link]();
int dest = [Link]();
addEdge(src, dest);
}

[Link]("Depth First Search (starting from vertex 0):");


DFS(0);

[Link]();
}}

You might also like