Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- fun equationsPossible(equations: Array<String>): Boolean {
- // To adjacency list and collect not equal variables
- val adjacencyList = Array<ArrayList<Int>>(26) { ArrayList(25) }
- val notEqualVariables = ArrayList<Pair<Int, Int>>(250)
- equations.forEach { equation ->
- val firstVar = equation[0].toInt() - 97
- val isEqual = equation[1] == '='
- val secondVar = equation[3].toInt() - 97
- if (isEqual) {
- adjacencyList[firstVar].add(secondVar)
- adjacencyList[secondVar].add(firstVar)
- } else {
- notEqualVariables.add(Pair(firstVar, secondVar))
- }
- }
- val used = HashSet<Int>(equations.size)
- val variableToComponent = java.util.HashMap<Int, Int>(equations.size)
- var componentId = -1
- // For each vertex
- for (i in 0..adjacencyList.lastIndex) {
- val neighbors = adjacencyList[i]
- // For each neighbor
- for (j in 0..neighbors.lastIndex){
- val v = neighbors[j]
- if (used.contains(v)) continue
- ++componentId
- dfs(adjacencyList, v, used, variableToComponent, componentId)
- }
- }
- notEqualVariables.forEach { pair ->
- if (pair.first == pair.second) {
- return false
- }
- if (variableToComponent[pair.first] != null && variableToComponent[pair.first] == variableToComponent[pair.second]) {
- return false
- }
- }
- return true
- }
- fun dfs(
- adjacencyList: Array<ArrayList<Int>>,
- curVertex: Int,
- used: HashSet<Int>,
- variableToComponent: HashMap<Int, Int>,
- componentId: Int
- ) {
- used.add(curVertex)
- variableToComponent.put(curVertex, componentId)
- val neighbors = adjacencyList[curVertex]
- for (i in 0..neighbors.lastIndex) {
- val v = neighbors[i]
- if (used.contains(v)) continue
- dfs(adjacencyList, v, used, variableToComponent, componentId)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement