LeetCode之All Paths From Source to Target(Kotlin)

问题:
Given a directed, acyclic graph of N nodes. Find all possible paths from node 0 to node N-1, and return them in any order.
The graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. graph[i] is a list of all nodes j for which the edge (i, j) exists.

Example:
Input: [[1,2], [3], [3], []]
Output: [[0,1,3],[0,2,3]]
Explanation: The graph looks like this:
0--->1
| |
v v
2--->3
There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.


方法:
深度优先遍历,按照数组中存储的路径遍历,遍历所有的path即可得到结果。

具体实现:

class AllPathsFromSourceToTarget {
    fun allPathsSourceTarget(graph: Array<IntArray>): List<List<Int>> {
        val result = mutableListOf<List<Int>>()
        val path = mutableListOf<Int>()
        path.add(0)
        dfsSearch(graph, path, result, 0)
        path.remove(0)
        return result
    }

    private fun dfsSearch(graph: Array<IntArray>, path: MutableList<Int>, result: MutableList<List<Int>>, node: Int) {
        if (node == graph.lastIndex) {
            result.add(ArrayList<Int>(path))
            return
        }
        for (nextNode in graph[node]) {
            path.add(nextNode)
            dfsSearch(graph, path, result, nextNode)
            path.remove(nextNode)
        }
    }
}

fun main(args: Array<String>) {
    val arrays = arrayOf(intArrayOf(1,2), intArrayOf(3), intArrayOf(3), intArrayOf())
    val allPathsFromSourceToTarget = AllPathsFromSourceToTarget()
    val result = allPathsFromSourceToTarget.allPathsSourceTarget(arrays)
}

有问题随时沟通

具体代码实现可以参考Github

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 那些锋刃 会追着时间疯长 我已能预见 那些伤 我会在风暴来临前 迎击而上 心的敏感 遗失在 你必经的路旁 请你将它...
    半盏星风阅读 182评论 2 4
  • 《延禧攻略》是今年暑假热播的一部剧,主要讲述宫女魏璎珞凭勇往直前的勇气、机敏灵活的头脑、宽广博大的胸怀,化解宫廷上...
    徐莹吖阅读 818评论 0 0
  • 详谈 Struts2 的核心概念 本文将深入探讨Struts2 的核心概念,首先介绍的是Struts2 的体系结构...
    可爱傻妞是我的爱阅读 1,260评论 0 2

友情链接更多精彩内容