Advertisement
Guest User

Untitled

a guest
Jun 15th, 2024
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.94 KB | None | 0 0
  1. fun equationsPossible(equations: Array<String>): Boolean {
  2.     // To adjacency list and collect not equal variables
  3.     val adjacencyList = Array<ArrayList<Int>>(26) { ArrayList(25) }
  4.     val notEqualVariables = ArrayList<Pair<Int, Int>>(250)
  5.     equations.forEach { equation ->
  6.         val firstVar = equation[0].toInt() - 97
  7.         val isEqual = equation[1] == '='
  8.         val secondVar = equation[3].toInt() - 97
  9.         if (isEqual) {
  10.             adjacencyList[firstVar].add(secondVar)
  11.             adjacencyList[secondVar].add(firstVar)
  12.         } else {
  13.             notEqualVariables.add(Pair(firstVar, secondVar))
  14.         }
  15.     }
  16.  
  17.     val used = HashSet<Int>(equations.size)
  18.     val variableToComponent = java.util.HashMap<Int, Int>(equations.size)
  19.     var componentId = -1
  20.     // For each vertex
  21.     for (i in 0..adjacencyList.lastIndex) {
  22.         val neighbors = adjacencyList[i]
  23.         // For each neighbor
  24.         for (j in 0..neighbors.lastIndex){
  25.             val v = neighbors[j]
  26.             if (used.contains(v)) continue
  27.             ++componentId
  28.             dfs(adjacencyList, v, used, variableToComponent, componentId)
  29.         }
  30.     }
  31.  
  32.     notEqualVariables.forEach { pair ->
  33.         if (pair.first == pair.second) {
  34.             return false
  35.         }
  36.         if (variableToComponent[pair.first] != null && variableToComponent[pair.first] == variableToComponent[pair.second]) {
  37.             return false
  38.         }
  39.     }
  40.     return true
  41. }
  42.  
  43. fun dfs(
  44.     adjacencyList: Array<ArrayList<Int>>,
  45.     curVertex: Int,
  46.     used: HashSet<Int>,
  47.     variableToComponent: HashMap<Int, Int>,
  48.     componentId: Int
  49. ) {
  50.     used.add(curVertex)
  51.     variableToComponent.put(curVertex, componentId)
  52.  
  53.     val neighbors = adjacencyList[curVertex]
  54.     for (i in 0..neighbors.lastIndex) {
  55.         val v = neighbors[i]
  56.         if (used.contains(v)) continue
  57.         dfs(adjacencyList, v, used, variableToComponent, componentId)
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement