|
| 1 | +class Solution { |
| 2 | + /** |
| 3 | + * @param n: An integer |
| 4 | + * @param edges: a list of undirected edges |
| 5 | + * @return: true if it's a valid tree, or false |
| 6 | + */ |
| 7 | + fun validTree(n: Int, edges: Array<IntArray>): Boolean { |
| 8 | + // write your code here |
| 9 | + val adj = List(n) {mutableListOf<Int>()} // S(V, E) = O(V + E) |
| 10 | + edges.forEach { |
| 11 | + adj[it[0]].add(it[1]) |
| 12 | + adj[it[1]].add(it[0]) |
| 13 | + } |
| 14 | + var t = 0 |
| 15 | + val tortoiseStack = mutableListOf<MutableList<Int>>(mutableListOf(0, 0, -1)) |
| 16 | + val hareStack = mutableListOf<MutableList<Int>>(mutableListOf(0, 0, -1)) |
| 17 | + var tortoise = listOf(-1) |
| 18 | + while (! hareStack.isEmpty()) { // T(V, E) = O(V + E) |
| 19 | + val hare = hareStack.last() |
| 20 | + if (hare[1] == adj[hare[0]].size) { |
| 21 | + hareStack.removeLast() |
| 22 | + } else if (adj[hare[0]][hare[1]] != hare[2]) { |
| 23 | + hareStack.add(mutableListOf(adj[hare[0]][hare[1]], 0, hare[0])) |
| 24 | + } |
| 25 | + if (hare[1]++ != 0) { |
| 26 | + continue |
| 27 | + } |
| 28 | + if ((t++ and 1) == 1) { |
| 29 | + while (! tortoiseStack.isEmpty()) { |
| 30 | + tortoise = tortoiseStack.last() |
| 31 | + if (tortoise[1] == adj[tortoise[0]].size) { |
| 32 | + tortoiseStack.removeLast() |
| 33 | + } else if (adj[tortoise[0]][tortoise[1]] != tortoise[2]) { |
| 34 | + tortoiseStack.add(mutableListOf(adj[tortoise[0]][tortoise[1]], 0, tortoise[0])) |
| 35 | + } |
| 36 | + if (tortoise[1]++ != 0) { |
| 37 | + continue |
| 38 | + } |
| 39 | + break |
| 40 | + } |
| 41 | + } |
| 42 | + if (hare[0] == tortoise[0]) { |
| 43 | + return false |
| 44 | + } |
| 45 | + } |
| 46 | + return t == n |
| 47 | + } |
| 48 | +} |
0 commit comments