Leetcode 797 所有可能的路徑 BFS 回溯
阿新 • • 發佈:2022-03-28
C:
#include <stdlib.h> #include <stdio.h> #include <string.h> int **reArr; int currentArr[15]; int currentArrSize; void search(int point, int **graph, int graphSize, int *graphColSize, int *returnSize, int **returnColumnSizes) { if (point == graphSize - 1) { int*currentRe = malloc(sizeof(int) * currentArrSize); memcpy(currentRe, currentArr, sizeof(int) * currentArrSize); reArr[*returnSize] = currentRe; (*returnColumnSizes)[(*returnSize)++] = currentArrSize; return; } int *nexts = graph[point]; int nextsSize = graphColSize[point];for (int i = 0; i < nextsSize; i++) { currentArr[currentArrSize++] = nexts[i]; search(nexts[i], graph, graphSize, graphColSize, returnSize, returnColumnSizes); currentArrSize--; } } /** * 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) { reArr = malloc(sizeof(int *) * 16384); *returnSize = 0; currentArrSize = 0; currentArr[currentArrSize++] = 0; *returnColumnSizes = malloc(sizeof(int) * 16384); search(0, graph, graphSize, graphColSize, returnSize, returnColumnSizes); return reArr; }
JAVA:
class Solution { final List<List<Integer>> anList = new LinkedList<List<Integer>>(); public final List<List<Integer>> allPathsSourceTarget(int[][] graph) { LinkedList<Integer> his = new LinkedList<Integer>(); his.add(0); search(graph, 0, his); return anList; } private final void search(int[][] graph, int currentPoint, LinkedList<Integer> his) { if (currentPoint == graph.length - 1) { anList.add(copyList(his)); return; } int[] nexts = graph[currentPoint]; for (int i = 0; i < nexts.length; i++) { his.add(nexts[i]); search(graph, nexts[i], his); his.removeLast(); } } private final List<Integer> copyList(List<Integer> list) { List<Integer> newList = new ArrayList<Integer>(list.size()); for (int i = 0; i < list.size(); i++) newList.add(list.get(i)); return newList; } }
JS:
var anList = []; /** * @param {number[][]} graph * @return {number[][]} */ var allPathsSourceTarget = function (graph) { anList = []; let his = []; his.push(0); search(graph, 0, his); return anList; }; var search = function (graph, currentPoint, his) { if (currentPoint == graph.length - 1) { anList.push(copyArr(his)); return; } let nexts = graph[currentPoint]; for (let i = 0; i < nexts.length; i++) { his.push(nexts[i]); search(graph, nexts[i], his); his.pop(); } } var copyArr = function (arr) { let re = new Array(arr.length); for (let i = 0; i < arr.length; i++) re[i] = arr[i]; return re; }
JAVA 表現亮眼