void calculate(TSPNodeData node) { nodes.Remove(node); if (node.level == dimension - 1) { this.path = node.path; this.cost = node.cost; return; } for (int k = 0; k < dimension; k++) { if (node.visited[k] == false) { double[,] newMatrix = MatrixUtil.Clone(node.matrix); double cij = newMatrix[node.index, k]; newMatrix[k, node.index] = Weight.Infinity; for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { if (i == node.index || j == k) { newMatrix[i, j] = Weight.Infinity; } } } double cost; double[,] reducedNewMatrix = ReduceMatrix(newMatrix, out cost); cost += cij + node.cost; bool[] visited = new bool[dimension]; int[] path = new int[dimension + 1]; Array.Copy(node.visited, visited, dimension); Array.Copy(node.path, path, dimension); visited[k] = true; path[node.level + 1] = k; nodes.Add(new TSPNodeData() { matrix = reducedNewMatrix, cost = cost, level = node.level + 1, visited = visited, index = k, path = path }); } } nodes.Sort(); calculate(nodes[0]); }
double[,] ReduceMatrix(double[,] mat, out double cost) { cost = 0; double[,] matrix = MatrixUtil.Clone(mat); for (int i = 0; i < matrix.GetLength(0); i++) { double min = Weight.Infinity; for (int j = 0; j < matrix.GetLength(1); j++) { if (min > matrix[i, j]) { min = matrix[i, j]; } } if (min > 0 && min != Weight.Infinity) { for (int j = 0; j < matrix.GetLength(1); j++) { matrix[i, j] -= min; } cost += min; } } for (int i = 0; i < matrix.GetLength(1); i++) { double min = Weight.Infinity; for (int j = 0; j < matrix.GetLength(0); j++) { if (min > matrix[j, i]) { min = matrix[j, i]; } } if (min > 0 && min != Weight.Infinity) { for (int j = 0; j < matrix.GetLength(1); j++) { matrix[j, i] -= min; } cost += min; } } return(matrix); }
/// <summary> /// 完全克隆 /// </summary> /// <returns></returns> public override IMatrix Clone() { return(new DiagonalMatrix(MatrixUtil.Clone(this._vector))); }
/// <summary> /// 完全克隆 /// </summary> /// <returns></returns> public override IMatrix Clone() { return(new SymmetricMatrix(MatrixUtil.Clone(this._vector))); }