//taking input of undirected graph using Adjacency Matrix
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); //denotes no. of vertices
int m = scanner.nextInt(); // no. of edges
int[][] adj = new int[n + 1][n + 1];
for (int i = 0; i < m; i++) {
int u = scanner.nextInt();
int v = scanner.nextInt();
adj[u][v] = 1;
adj[v][u] = 1; // this statement will be removed in case of a directed
graph
}
// Rest of your code goes here
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
System.out.print(adj[i][j] + " ");
}
System.out.println();
}
}
}
input output with test cases
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Test case 1
System.out.println("Test Case 1:");
int n1 = 4;
int m1 = 3;
int[][] adj1 = new int[n1 + 1][n1 + 1];
for (int i = 0; i < m1; i++) {
int u = scanner.nextInt();
int v = scanner.nextInt();
adj1[u][v] = 1;
adj1[v][u] = 1;
}
printGraph(adj1);
// Test case 2
System.out.println("\nTest Case 2:");
int n2 = 5;
int m2 = 4;
int[][] adj2 = new int[n2 + 1][n2 + 1];
for (int i = 0; i < m2; i++) {
int u = scanner.nextInt();
int v = scanner.nextInt();
adj2[u][v] = 1;
adj2[v][u] = 1;
}
printGraph(adj2);
// scanner.close();
}
private static void printGraph(int[][] adj) {
System.out.println("Adjacency Matrix:");
for (int i = 1; i < adj.length; i++) {
for (int j = 1; j < adj[i].length; j++) {
System.out.print(adj[i][j] + " ");
}
System.out.println();
}
System.out.println("\nGraph:");
for (int i = 1; i < adj.length; i++) {
System.out.print(i + ": ");
for (int j = 1; j < adj[i].length; j++) {
if (adj[i][j] == 1) {
System.out.print(j + " ");
}
}
System.out.println();
}
System.out.println();
}
}
take input edges of both case
both no. vertices and edges are taken already in above code
input output using Adjacency Lists
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
ArrayList<Integer>[] adj = new ArrayList[n + 1];
for (int i = 1; i <= n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int u = scanner.nextInt();
int v = scanner.nextInt();
adj[u].add(v);
adj[v].add(u);
}
// Print the graph
System.out.println("Graph:");
for (int i = 1; i <= n; i++) {
System.out.print(i + ": ");
for (int neighbor : adj[i]) {
System.out.print(neighbor + " ");
}
System.out.println();
}
scanner.close();
}
}
//for weighted graph
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
// adjacency list for weighted undirected graph
ArrayList<Edge>[] adj = new ArrayList[n + 1];
for (int i = 1; i <= n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int u = scanner.nextInt();
int v = scanner.nextInt();
int weight = scanner.nextInt();
adj[u].add(new Edge(v, weight));
adj[v].add(new Edge(u, weight));
}
// Print the graph
System.out.println("Weighted Graph:");
for (int i = 1; i <= n; i++) {
System.out.print(i + ": ");
for (Edge edge : adj[i]) {
System.out.print("(" + edge.destination + ", " + edge.weight + ")
");
}
System.out.println();
}
scanner.close();
}
static class Edge {
int destination;
int weight;
public Edge(int destination, int weight) {
this.destination = destination;
this.weight = weight;
}
}
}
public ArrayList<Integer> bfsOfGraph(int V,
ArrayList<ArrayList<Integer>> adj) {
ArrayList < Integer > bfs = new ArrayList < > ();
boolean vis[] = new boolean[V];
Queue < Integer > q = new LinkedList < > ();
q.add(0);
vis[0] = true;
while (!q.isEmpty()) {
Integer node = q.poll();
bfs.add(node);
// Get all adjacent vertices of the dequeued vertex s
// If a adjacent has not been visited, then mark it
// visited and enqueue it
for (Integer it: adj.get(node)) {
if (vis[it] == false) {
vis[it] = true;
q.add(it);
}
}
}
return bfs;
}
// DFS
class Solution {
// Function to return a list containing the DFS traversal of the graph.
public static void dfs(int node, boolean vis[], ArrayList<ArrayList<Integer>>
adj,
ArrayList<Integer> ls) {
//marking current node as visited
vis[node] = true;
ls.add(node);
//getting neighbour nodes
for(Integer it: adj.get(node)) {
if(vis[it] == false) {
dfs(it, vis, adj, ls);
}
}
}
// Function to return a list containing the DFS traversal of the graph.
public ArrayList<Integer> dfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj)
{
//boolean array to keep track of visited vertices
boolean vis[] = new boolean[V+1];
vis[0] = true;
ArrayList<Integer> ls = new ArrayList<>();
dfs(0, vis, adj, ls);
return ls;
}
}
Number of provinces
class Solution {
// dfs traversal function
private static void dfs(int node,
ArrayList<ArrayList<Integer>> adjLs ,
int vis[]) {
vis[node] = 1;
for(Integer it: adjLs.get(node)) {
if(vis[it] == 0) {
dfs(it, adjLs, vis);
}
}
}
static int numProvinces(ArrayList<ArrayList<Integer>> adj, int V) {
ArrayList<ArrayList<Integer>> adjLs = new ArrayList<ArrayList<Integer>>();
for(int i = 0;i<V;i++) {
adjLs.add(new ArrayList<Integer>());
}
// to change adjacency matrix to list
for(int i = 0;i<V;i++) {
for(int j = 0;j<V;j++) {
// self nodes are not considered
if(adj.get(i).get(j) == 1 && i != j) {
adjLs.get(i).add(j);
adjLs.get(j).add(i);
}
}
}
int vis[] = new int[V];
int cnt = 0;
for(int i = 0;i<V;i++) {
if(vis[i] == 0) {
cnt++;
dfs(i, adjLs, vis);
}
}
return cnt;
}
};
///Topological sort
import java.util.*;
class Solution {
private static void dfs(int node, int vis[], Stack<Integer> st,
ArrayList<ArrayList<Integer>> adj) {
vis[node] = 1;
for (int it : adj.get(node)) {
if (vis[it] == 0)
dfs(it, vis, st, adj);
}
st.push(node);
}
// Function to return list containing vertices in Topological order.
static int[] topoSort(int V, ArrayList<ArrayList<Integer>> adj) {
int vis[] = new int[V];
Stack<Integer> st = new Stack<Integer>();
for (int i = 0; i < V; i++) {
if (vis[i] == 0) {
dfs(i, vis, st, adj);
}
}
int ans[] = new int[V];
int i = 0;
while (!st.isEmpty()) {
ans[i++] = st.peek();
st.pop();
}
return ans;
}
}
//using bfs
import java.util.*;
class Solution {
public ArrayList<Integer> topoSort(int V, ArrayList<Integer>[] adj) {
int[] inDegree = new int[V];
Queue<Integer> queue = new LinkedList<>();
// Calculate in-degrees for each vertex
for (int i = 0; i < V; i++) {
for (int neighbor : adj[i]) {
inDegree[neighbor]++;
}
}
// Add vertices with in-degree 0 to the queue
for (int i = 0; i < V; i++) {
if (inDegree[i] == 0) {
queue.offer(i);
}
}
ArrayList<Integer> result = new ArrayList<>();
while (!queue.isEmpty()) {
int node = queue.poll();
result.add(node);
// Reduce in-degree of neighbors and enqueue if in-degree becomes 0
for (int neighbor : adj[node]) {
inDegree[neighbor]--;
if (inDegree[neighbor] == 0) {
queue.offer(neighbor);
}
}
}
return result;
}
}
public class Main {
public static void main(String[] args) {
int V = 6;
ArrayList<Integer>[] adj = new ArrayList[V];
for (int i = 0; i < V; i++) {
adj[i] = new ArrayList<>();
}
adj[2].add(3);
adj[3].add(1);
adj[4].add(0);
adj[4].add(1);
adj[5].add(0);
adj[5].add(2);
Solution obj = new Solution();
ArrayList<Integer> ans = obj.topoSort(V, adj);
for (int node : ans) {
System.out.print(node + " ");
}
System.out.println();
}
}
Shortest path in DAG using topological sort
//https://www.geeksforgeeks.org/problems/shortest-path-in-undirected-graph/1
class Pair {
int first, second;
Pair(int _first, int _second) {
this.first = _first;
this.second = _second;
}
}
//User function Template for Java
class Solution {
private void topoSort(int node, ArrayList < ArrayList < Pair >> adj,
int vis[], Stack < Integer > st) {
//This is the function to implement Topological sort.
vis[node] = 1;
for (int i = 0; i < adj.get(node).size(); i++) {
int v = adj.get(node).get(i).first;
if (vis[v] == 0) {
topoSort(v, adj, vis, st);
}
}
st.add(node);
}
public int[] shortestPath(int N, int M, int[][] edges) {
ArrayList < ArrayList < Pair >> adj = new ArrayList < > ();
for (int i = 0; i < N; i++) {
ArrayList < Pair > temp = new ArrayList < Pair > ();
adj.add(temp);
}
//We create a graph first in the form of an adjacency list.
for (int i = 0; i < M; i++) {
int u = edges[i][0];
int v = edges[i][1];
int wt = edges[i][2];
adj.get(u).add(new Pair(v, wt));
}
int vis[] = new int[N];
//Now, we perform topo sort using DFS technique
//and store the result in the stack st.
Stack < Integer > st = new Stack < > ();
for (int i = 0; i < N; i++) {
if (vis[i] == 0) {
topoSort(i, adj, vis, st);
}
}
//Further, we declare a vector ‘dist’ in which we update the value of the
nodes’
//distance from the source vertex after relaxation of a particular node.
int dist[] = new int[N];
for (int i = 0; i < N; i++) {
dist[i] = (int)(1e9);
}
dist[0] = 0;
while (!st.isEmpty()) {
int node = st.peek();
st.pop();
for (int i = 0; i < adj.get(node).size(); i++) {
int v = adj.get(node).get(i).first;
int wt = adj.get(node).get(i).second;
if (dist[node] + wt < dist[v]) {
dist[v] = wt + dist[node];
}
}
}
for (int i = 0; i < N; i++) {
if (dist[i] == 1e9) dist[i] = -1;
}
return dist;
}
}
//shortest path in undirected graph with unit weights
https://www.geeksforgeeks.org/problems/shortest-path-in-undirected-
graph-having-unit-distance/1
public int[] shortestPath(int[][] edges,int n,int m ,int src) {
//Create an adjacency list of size N for storing the undirected graph.
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i = 0;i<n;i++) {
adj.add(new ArrayList<>());
}
for(int i = 0;i<m;i++) {
adj.get(edges[i][0]).add(edges[i][1]);
adj.get(edges[i][1]).add(edges[i][0]);
}
//A dist array of size N initialised with a large number to
//indicate that initially all the nodes are untraversed.
int dist[] = new int[n];
for(int i = 0;i<n;i++) dist[i] = (int)1e9;
dist[src] = 0;
// BFS Implementation
Queue<Integer> q = new LinkedList<>();
q.add(src);
while(!q.isEmpty()) {
int node = q.peek();
q.remove();
for(int it : adj.get(node)) {
if(dist[node] + 1 < dist[it]) {
dist[it] = 1 + dist[node];
q.add(it);
}
}
}
// Updated shortest distances are stored in the resultant array ‘ans’.
// Unreachable nodes are marked as -1.
for(int i = 0;i<n;i++) {
if(dist[i] == 1e9) {
dist[i] = -1;
}
}
return dist;
}
}
class Pair{
int node;
int distance;
public Pair(int distance,int node){
this.node = node;
this.distance = distance;
}
}
//User function Template for Java
class Solution
{
//Function to find the shortest distance of all the vertices
//from the source vertex S.
static int[] dijkstra(int V, ArrayList<ArrayList<ArrayList<Integer>>> adj, int
S)
{
// Create a priority queue for storing the nodes as a pair {dist, node
// where dist is the distance from source to the node.
PriorityQueue<Pair> pq =
new PriorityQueue<Pair>((x,y) -> x.distance - y.distance);
int []dist = new int[V];
// Initialising distTo list with a large number to
// indicate the nodes are unvisited initially.
// This list contains distance from source to the nodes.
for(int i = 0;i<V;i++) dist[i] = (int)(1e9);
// Source initialised with dist=0.
dist[S] = 0;
pq.add(new Pair(0,S));
// Now, pop the minimum distance node first from the min-heap
// and traverse for all its adjacent nodes.
while(pq.size() != 0) {
int dis = pq.peek().distance;
int node = pq.peek().node;
pq.remove();
// Check for all adjacent nodes of the popped out
// element whether the prev dist is larger than current or not.
for(int i = 0;i<adj.get(node).size();i++) {
int edgeWeight = adj.get(node).get(i).get(1);
int adjNode = adj.get(node).get(i).get(0);
// If current distance is smaller,
// push it into the queue.
if(dis + edgeWeight < dist[adjNode]) {
dist[adjNode] = dis + edgeWeight;
pq.add(new Pair(dist[adjNode], adjNode));
}
}
}
// Return the list containing shortest distances
// from source to all the nodes.
return dist;
}
}