Give me 5 minutes to show you the object-oriented description of all graph algorithms

Hello, I'm Xiao Huang, a Java development engineer in Unicorn enterprise.
The school recruits dozens of offer s, with an average annual salary of 20W~40W.
Thank you for meeting us in the vast sea of people,
As the saying goes: when your talent and ability are not enough to support your dream, please calm down and learn,
I hope you can study and work hard with me to realize your dream.

1, Foreword

For the picture, I have always been confused

What you understand is the meaning of the graph, but what you don't understand is the specific implementation of the graph

For the chart questions interviewed by major factories at present, there are no more than the following points:

  • Depth first search, breadth first search: DFS, BFS
  • Minimum spanning tree: Kruskal, Prim
  • Shortest path: Dijkstra, Dijkstra enhanced heap version
  • Topology sort: TopologicalSort

In fact, these algorithms don't sound too difficult to understand, but when we really write code, we will find that the edges and points of the fool's diagram are too difficult to describe, resulting in the absence of people who write and can't get in and out

This series of articles will describe the generation of a graph from the perspective of objects, and introduce all the above algorithms with the simplest idea. Let's go into this article.

2, What is a graph

The figure is an abstraction of the connection relationship in our real life, such as the attention relationship of the circle of friends and microblog.

The simple abstraction is shown in the figure below:

The graph is divided into directed graph and undirected graph, as shown in the following figure:


We can see that a directed graph represents that only one vertex can reach another vertex, while an undirected graph represents that two vertices can reach each other.

  • In Figure 1, V4 reaches V1, but V1 cannot reach v4
  • In Figure 2, V4 reaches V1, and V1 can also reach v4

Of course, there is another form of graph, called weighted graph (mainly used to calculate the distance and toll), as shown in the figure below:

3, How to store the structure of a graph

When we brush the questions, the examples given to us by the questions are often like this: 743. Network delay time

The topic will give us a two-dimensional matrix. A row of matrix has three numbers: starting point, ending point and weight

How to express this two-dimensional matrix has become a difficult thing for us in drawing problems

This paper will directly use a special representation to solve this problem. We start with the most basic representation of adjacency matrix and adjacency table

1. Adjacency matrix

Adjacency matrix is a matrix that represents the adjacency relationship between vertices in a graph.

  • For adjacency matrix of undirected graph: symmetric matrix: int [] []
  • Adjacency matrix of a directed graph: the sum of rows is out degree, and the sum of columns is in degree
  • Adjacency matrix of weighted graph

2. Adjacency table

Adjacency list is a linked storage structure, similar to linked list array.

  • Adjacency table of undirected graph: HashMap < integer, ArrayList < integer > >

3. Graph object representation

Let's think about the image of the above two methods for the representation of graphs?

Although some problems are very comfortable when expressed by matrix, let's think about it. When we find the minimum spanning tree and unlock the points by using the connection of edges, using matrix will
It doesn't feel very abstract and difficult to understand. As shown in, we need to customize a graph representation method to enhance our understanding of graphs

For the graph, let's think about what it mainly includes?

A graph is a structure composed of points and edges, that is, if we want to draw a graph, we must have: points and edges

Description of the point:

  • Value of point: int value
  • Adjacent points: ArrayList < node > nexts
  • Adjacent edges: ArrayList < edge > edges
  • Penetration: int in
  • Output: int out
public class Node {
    public int value;
    public int in;
    public int out;
    public ArrayList<Node> nexts;
    public ArrayList<Edge> edges;

    public Node(int value) {
        this.value = value;
        in = 0;
        out = 0;
        nexts = new ArrayList<>();
        edges = new ArrayList<>();
    }
}

Description of the edge:

  • From where: Node from
  • Where to go: Node to
  • Edge weights: int weight
public class Edge {
    Node from;
    Node to;
    int weight;

    public Edge(Node from, Node to, int weight) {
        this.from = from;
        this.to = to;
        this.weight = weight;
    }
}

Description of the diagram:

  • Collection of multiple points: HashMap < integer, node > nodes
  • Set of multiple edges: set < edge > edges
public class Graph {
    public HashMap<Integer, Node> nodes;
    public Set<Edge> edges;

    public Graph() {
        nodes = new HashMap<>();
        edges = new HashSet<>();
    }
}

There may be some questions here. Although you write like this, how can you transform it?

Don't worry, let's transform.

public static Graph createGraph(int[][] matrix) {
        // Initialize a graph
        Graph graph = new Graph();

        for (int[] arr : matrix) {
            // Come on
            int from = arr[0];
            // Where to go
            int to = arr[1];
            // weight
            int value = arr[2];

            // Generate corresponding points
            Node fromNode = new Node(from);
            Node toNode = new Node(to);

            // Check whether there is information about this point at present
            if (!graph.nodes.containsKey(from)) {
                graph.nodes.put(from, fromNode);
            }
            if (!graph.nodes.containsKey(to)) {
                graph.nodes.put(to, toNode);
            }

            // Generate an edge (where the edge is a directed edge)
            Edge edge = new Edge(fromNode, toNode, value);

            // Add an edge inside the point
            graph.nodes.get(from).edges.add(edge);

            //  Add the next point to the point
            graph.nodes.get(from).nexts.add(toNode);

            // Add in and out points
            graph.nodes.get(from).out++;
            graph.nodes.get(to).in++;

            // Add edges in the figure
            graph.edges.add(edge);

        }
        return graph;
    }

When we have finished the transformation, we will test:

	public static void main(String[] args) {
        int[][] arr = new int[][]{{2, 1, 1}, {2, 3, 1}, {3, 4, 1}};
        Graph graph = createGraph(arr);
        // What are the edges starting from 2
        List<Edge> edgeList = graph.nodes.get(2).edges;
        for (Edge edge : edgeList) {
            System.out.println("from" + edge.from.value + "---->" + edge.to.value + "Weight is" + edge.weight);
        }
    }

Final result:

From 2---->1 The weight is 1
 From 2---->3 The weight is 1

In the future, when we do questions, we can save the conversion code and call it directly

A simple image of our picture

4, Function of graph

The diagram is often used in the following places:

  • Depth first search, breadth first search: DFS, BFS
  • Minimum spanning tree: Kruskal, Prim
  • Shortest path: Dijkstra, Dijkstra enhanced heap version
  • Topology sort: TopologicalSort

The following chapters will slowly explain all the above applications

The content of this issue is here. Algorithm source code can be answered in WeChat official account: algorithm source code, you can get links, next will tell DFS and BFS algorithm.

I am a Java development engineer of Unicorn enterprise. I hope you can pay attention. If you have any problems, you can leave a message or send a private message to me via wechat. See you next time!

Tags: Java Algorithm leetcode Interview

Posted on Wed, 13 Oct 2021 23:56:14 -0400 by dylan001