Created
March 25, 2021 14:08
-
-
Save chenharryhua/88cacc965dd58e37ceaf4f7a80b6c573 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://www.hackerrank.com/challenges/bfsshortreach/problem | |
def height(neighbors: Map[Int, Set[Int]], level: Int, stack: Set[Int], rst: Map[Int, Int]): Map[Int, Int] = | |
if (stack.isEmpty) rst | |
else { | |
val known = stack.filterNot(rst.contains).map((_ -> level)).toMap ++ rst | |
val set = stack.flatMap(neighbors.get).flatten.filterNot(known.contains) | |
height(neighbors, level + 1, set, known) | |
} | |
def bfs(n: Int, m: Int, edges: Array[Array[Int]], s: Int): Array[Int] = { | |
val neighbors = edges.foldLeft(Map.empty[Int, Set[Int]]) { case (m, Array(from, to)) => | |
m.updatedWith(from)(_.map(_ + to).orElse(Some(Set(to)))).updatedWith(to)(_.map(_ + from).orElse(Some(Set(from)))) | |
} | |
val map = height(neighbors, 1, neighbors.getOrElse(s, Set()), Map.empty) | |
(1 to n).filterNot(_ == s).map(x => map.get(x).map(_ * 6).getOrElse(-1)).toArray | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment