给一个有 n 个结点的有向无环图,找到所有从 0 到 n-1 的路径并输出(不要求按顺序)
二维数组的第 i 个数组中的单元都表示有向图中 i 号结点所能到达的下一些结点(译者注:有向图是有方向的,即规定了 a→b 你就不能从
b→a )空就是没有下一个结点了。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/all-paths-from-source-to-target
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
int **graph_temp = NULL;
int *graphColSize_temp = NULL;
int retSize = 0;
int *retColSize = NULL;
int **ret = NULL;
int *arrays = NULL;
void backtrack(int index, int target, int len)
{
if(index == target)
{
int *temp = (int *)malloc(sizeof(int) * (len+1));
memcpy(temp, arrays, sizeof(int) * len);
temp[len] = target; //终点为目标值
ret[retSize] = temp;
retColSize[retSize++] = len;
return;
}
char l = graphColSize_temp[index];
for(int i = 0; i < l; i++)
{
arrays[len] = graph_temp[index][i];
backtrack(graph_temp[index][i], target, len+1);
arrays[len] = 0;
}
}
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** allPathsSourceTarget(int** graph, int graphSize, int* graphColSize, int* returnSize, int** returnColumnSizes){
graph_temp = graph;
graphColSize_temp = graphColSize;
retSize = 0;
retColSize = (int *)malloc(sizeof(int) * 7000);
ret = (int**)malloc(sizeof(int*) * 7000);
arrays = (int *)malloc(sizeof(int) * 16);
arrays[0] = 0; //起点为0
backtrack(0, graphSize - 1, 1);
free(arrays);
*returnSize = retSize;
*returnColumnSizes = retColSize;
return ret;
}
思路:回溯算法
逻辑清楚即可