var arr = [["A", "B"], ["C", "D"], ["E", "F"], ["G", "H"], ["C", "A"],["C","Q"] ["F", "D"], ["E", "G"],["H", "A"]];
var point = "A";//根据arr二维数组进行接龙,point这个是接龙的起点和终点
//要求输出:output_arr=[["A", "C"],["C", "D"],["D", "F"],["F", "E"],["E", "G"],["G", "H"],["H", "A"]]
//如上,起点和终点都为"A"
//用不到的元素舍弃了:["A", "B"]中"A"以后的"B"再接不下去,所以没用,同理["C","Q"]中的"Q"也接不下去,也不用了
//注意顺序:["C", "A"],因为从"A"开始,所以这个元素变为["A","C"]
I am not engaged in this field of work. I write programs myself. When I encounter the above problem, it has been bothering me for several days. Please help me.
Provide a single solution idea.
First find the array whose first element is A, take it out and name it the candidate array
Then select one of the candidate arrays, and then define a current array and a result array to store the current head and tail sum results, such as [A,B] and [[A,B], [B,C]], Of course, the current array does not need to be used. Here is a convenient explanation.
Then loop arr until you know the array whose first letter is A, such as [B,C]. This result array can be collapsed into [A,C]. Then of course you need to save [B, C] into the result array, and delete [B, C] from arr.
Then if the current array is folded to length 0 after grouping, it means that a dragon has been found, and the result can be output.
But if it cannot be found, it means that [B, C] has no solution, then the result array and the current array will be returned to the previous stage, and [B, C] will no longer be added to arr, because It can't be one of the answers. Then keep repeating this process.
The description of the image point is that we find that [A, B, B, C, C, D] cannot find the result, fall back to [A, B, B, C], and then cannot find it, then continue to fall back to [ A,B]. And so on.
Find out until the end.
If there are multiple interpretations, it is exactly the same solution. Too troublesome.
This is an exhaustive exercise...
The idea I can think of is to select two ends and exhaustively search towards the middle.
Record each pair of possibilities (note that they are locked and cannot be selected repeatedly), and the end of the possibilities can be If you can catch it, it’s ok.
Since the length of the results is uncertain, and the order is also uncertain, this is much more complicated...
It took me some time to write a recursion and used a pruning logic. If a letter only appears once, then the corresponding letter pair will be removed from the original data.