You must have used drawing in windows. How is the paint bucket function implemented in the drawing?
This problem can be solved through the DFS deep priority search.
Target
The goal is to infer whether a certain two nodes are connected within a constant time.
The previous chapter introduces and queries the set algorithm, and the query set can solve the problem. The second method is DFS deep search.
Create an object to solve the problem. The outline of the object is as follows:
Public class connectedcomponnent {public connectedcomponnent (graph G) {}// infer whether two vertices are connected to public Boolean connected (int v, int W) {}// number of connected parts public int count () {}// ID of the connected part where the vertex is located public int ID (INT v ){}}
Mathematical definition
It is inferred whether the two vertices are connected to an equivalent relationship in discrete mathematics, which has:
Reflective: V and V are connected.
Symmetry: If V and W are connected, W and V are also connected.
Transmission: Assume that V and W are connected, and w and z are connected.
Definition of a connected part: the largest set of connected vertices.
Problem Solving
To solve the preceding problems, we must first pre-process the graph. The goal of preprocessing is to differentiate connected parts in the graph.
The process of distinguishing connected parts is as follows:
Mark all vertices as not asking
For each vertex that has not been asked, use DFS to mark the part number
Code
Public class connectedcomponnent {private Boolean [] visited; private int [] ID; private int count; Public connectedcomponnent (graph G) {visited = new Boolean [g.v ()]; id = new int [g.v ()]; CC (g) ;}// infer whether the two vertices are connected to the public Boolean connected (int v, int W) {return ID [v] = ID [w];} // number of connected parts public int count () {return count ;} // public int ID (INT v) {return ID [v];} private void CC (Graph G) {for (INT I = 0; I <g.v (); I ++) {If (! Visited [I]) {DFS (G, I); count ++; // Note: This sentence cannot be placed outside of if. Otherwise, count is always equal to the number of vertices }}private void DFS (graph G, int v) {visited [v] = true; Id [v] = count; For (int w: g. adj (V) {If (! Visited [w]) {DFS (G, W );}}}}
Application
Is the interpersonal relationship diagram of a university. If we regard interpersonal relationships as a graph, we can see very clearly that there are large and small connected parts.
Explore the number of stars in the sky chart.