OneCompiler

Finding path in cyclic graph if exists with BFS.

265
 import java.util.*

enum class Vertex {
    A, B, C, D, E
}

data class Edge(val source: Vertex, val dest: Vertex, val distance: Double, val time: Double)

fun findPath(source: Vertex, dest: Vertex, edges: Array<Edge>): List<Edge>? {
    val numVertices = Vertex.values().size
    val adjacencyList = Array(numVertices) { mutableListOf<Edge>() }
    
    for (edge in edges) {
        adjacencyList[edge.source.ordinal].add(edge)
    }
    
    val visited = BooleanArray(numVertices)
    val parent = Array<Edge?>(numVertices) { null }
    
    val queue: Queue<Vertex> = LinkedList<Vertex>()
    queue.add(source)
    visited[source.ordinal] = true
    
    while (!queue.isEmpty()) {
        val currVertex = queue.poll()
        
        for (edge in adjacencyList[currVertex.ordinal]) {
            val nextVertex = edge.dest
            
            if (!visited[nextVertex.ordinal]) {
                visited[nextVertex.ordinal] = true
                parent[nextVertex.ordinal] = edge
                queue.add(nextVertex)
                
                if (nextVertex == dest) {
                    // Found the destination vertex, build the path and return it
                    val path = mutableListOf<Edge>()
                    var currEdge = parent[dest.ordinal]
                    while (currEdge != null) {
                        path.add(currEdge)
                        currEdge = parent[currEdge.source.ordinal]
                    }
                    return path.reversed()
                }
            }
        }
    }
    
    // No path found from source to destination
    return null
}

fun main() {
    val edges = arrayOf(
        Edge(Vertex.A, Vertex.B, 10.0, 5.0),
        Edge(Vertex.B, Vertex.C, 15.0, 7.5),
        Edge(Vertex.C, Vertex.D, 12.0, 6.0),
        Edge(Vertex.D, Vertex.E, 20.0, 10.0), // search for A to E path then only it will showŒ
        Edge(Vertex.A, Vertex.E, 50.0, 20.0)
    )
    
    val source = Vertex.A
    val dest = Vertex.E
    
    val path = findPath(source, dest, edges)
    
    if (path != null) {
        println("Path found from $source to $dest:")
        for (edge in path) {
            println("${edge.source} -> ${edge.dest} (distance = ${edge.distance}, time = ${edge.time})")
        }
    } else {
        println("No path found from $source to $dest")
    }
}