Graphs 101

Graphs 101

Graph is a non-linear data structure that consists of nodes that are connected via edges.

Nodes are circles. They store data. There is no specific ordering for these nodes.

Graphs can be directed or undirected. Undirected graph are bi-directional. There is no direction associated with each node.

In directed graph each edge is directed from one vertex to the other. It contains ordered pair of vertices.

Cycles

A graph is said to have a cycle if it starts from a node and ends at the same node.

Degree of a graph

It is the number of edges that go inside and outside of a node.

For directed graph:

In this technique all the nodes are traversed in a breadth wise manner.

class bfs{

   public static ArrayList<Integer> bfsOnGraph(int v, ArrayList<ArrayList<Integer>> adj){
      ArrayList<Integer> bfs = new ArrayList<>();
      boolean[] visited = new boolean[v];
      Queue<Integer> queue = new LinkedList<>();

      queue.add(0);
      visited[0] = true;

      while(!queue.isEmpty()){
          Integer node = queue.poll();
          bfs.add(node);

          for(Integer it : adj.get(node)){
             if(visited[it] == false){
                 visited[it] = true;
                 queue.add(it);
             }

          }
      } 
      return bfs;
   }
}

All nodes are traversed in depth-wise manner.

public class dfs{
    public static void dfs(int node, boolean[] visited, ArrayList<ArrayList<Integer>> adj, ArrayList<Integer> list){
        visited[node] = true;
        list.add(node);

        for(Integer it : adj.get(node)){
            if(visited[it] == false){
                dfs(it, visited, adj, list);
            }
        }
    }


    public static ArrayList<Integer> dfsOnGraph(int v, ArrayList<Arraylist<Integer>> adj){
        boolean[] visited = new boolean[v];
        ArrayList<Integer> list = new ArrayList<>();

        visited[0] = true;
        dfs(0,visited, adj,ls);
        return list;

    }
}

Did you find this article valuable?

Support Reuben's blog by becoming a sponsor. Any amount is appreciated!