AlgorithmProgramQuestion:
The company has only one pen question, which should be completed within 10 minutes.
The following is a question: Use the six numbers 1, 2, 2, 3, 4, and 5 to write a main function in Java and print out all the different arrays, for example: 512234, 412345, etc., requirements: "4" cannot be In the third place, "3" and "5" cannot be connected.
Basic Ideas:
1. The problem is caused by the traversal of the graph structure. In fact, six numbers are six nodes, and six nodes are connected to a undirected connected graph. For each node, find the traversal path of the graph, the traversal path of all nodes is the final result set of the arrangement and combination of the six numbers.
2. Obviously, this result set does not meet the requirement of the question. Consider the following:
1. 3 and 5 cannot be connected: Actually, the nodes of the connected graph cannot be connected between 3 and 5. You can modify the graph structure and traverse the graph.
2. There can be no duplicates: Considering there are two duplicates, The result set can be put in the treeset to filter duplicate results.
Cannot be in the third place: the results that meet this condition are still removed from the result set.
Use a two-dimensional array to define the graph structure.CodeYes:
Import java. util. iterator;
Import java. util. treeset;
Public class testquestion {
Private string [] B = new string [] {"1", "2", "2", "3", "4", "5 "};
Private int n = B. length;
Private Boolean [] visited = new Boolean [N];
Visited = falsh;
Private int [] [] A = new int [N] [N];
Private string result = "";
Private treeset = new treeset ();
Public static void main (string [] ARGs ){
New testquestion (). Start ();
}
Private void start (){
For (INT I = 0; I <n; I ++ ){
For (Int J = 0; j <n; j ++ ){
If (I = J ){
A [I] [J] = 0;
} Else {
A [I] [J] = 1;
}
}
} A [3] [5] = 0;
A [5] [3] = 0;
For (INT I = 0; I <n; I ++ ){
This. depthfirstsearch (I );
}
Iterator it = set. iterator ();
While (it. hasnext ()){
String string = (string) it. Next ();
If (string. indexof ("4 ")! = 2 ){
System. Out. println (string );
}
}
}
Private void depthfirstsearch (INT startindex ){
Visited [startindex] = true;
Result = Result + B [startindex];
If (result. Length () = N ){
Treeset. Add (result );
}
For (Int J = 0; j <n; j ++ ){
If (A [startindex] [J] = 1 & visited [J] = false ){
Depthfirstsearch (j );
} Else {
Continue;
}
}
Result = result. substring (0, result. Length ()-1 );
Visited [startindex] = false;
}
}
Note: depressed, it took more than half an hour to write it out. Let's see the prompt !!! Undirected graph, learning data structures doesn't catch a cold for him