|
| 1 | +package kotlin |
| 2 | + |
| 3 | +import java.util.* |
| 4 | + |
| 5 | +class Solution { |
| 6 | + fun isBipartiteDfs(graph: Array<IntArray>): Boolean { |
| 7 | + if (graph.isEmpty()) return true |
| 8 | + |
| 9 | + val nodeColorMap = mutableMapOf<Int, Color>() |
| 10 | + fun dfs(node: Int, defaultColor: Color): Boolean { |
| 11 | + if (node !in nodeColorMap.keys) nodeColorMap[node] = defaultColor |
| 12 | + for (adjacentNode in graph[node]) { |
| 13 | + val isEdgeVisited = nodeColorMap[adjacentNode] != null |
| 14 | + if (isEdgeVisited) { |
| 15 | + val colorOfCurrentNode = nodeColorMap.getValue(node) |
| 16 | + val colorOfAdjacentNode = nodeColorMap.getValue(adjacentNode) |
| 17 | + if (colorOfAdjacentNode == colorOfCurrentNode) return false |
| 18 | + else continue |
| 19 | + } |
| 20 | + if (!dfs(adjacentNode, defaultColor.inverse)) return false |
| 21 | + } |
| 22 | + return true |
| 23 | + } |
| 24 | + |
| 25 | + for (node in graph.indices) { |
| 26 | + if (node in nodeColorMap.keys) continue |
| 27 | + if (!dfs(node, Color.RED)) return false |
| 28 | + } |
| 29 | + return true |
| 30 | + } |
| 31 | + |
| 32 | + fun isBipartiteBfs(graph: Array<IntArray>): Boolean { |
| 33 | + if (graph.isEmpty()) return true |
| 34 | + val nodeColorMap = mutableMapOf<Int, Color>() |
| 35 | + |
| 36 | + fun bfs(startNode: Int): Boolean { |
| 37 | + // if the node is already colored, return true |
| 38 | + if (startNode in nodeColorMap.keys) return true |
| 39 | + nodeColorMap[startNode] = Color.RED |
| 40 | + |
| 41 | + val queue = (LinkedList<Int>() as Queue<Int>).apply { add(startNode) } |
| 42 | + while (queue.isNotEmpty()) { |
| 43 | + val currentNode = queue.remove() |
| 44 | + val colorOfCurrentNode = nodeColorMap.getValue(currentNode) |
| 45 | + for (adjacentNode in graph[currentNode]) { |
| 46 | + if (adjacentNode in nodeColorMap.keys) { |
| 47 | + val colorOfAdjacentNode = nodeColorMap.getValue(adjacentNode) |
| 48 | + if (colorOfAdjacentNode == colorOfCurrentNode) return false |
| 49 | + continue |
| 50 | + } |
| 51 | + nodeColorMap[adjacentNode] = colorOfCurrentNode.inverse |
| 52 | + queue.add(adjacentNode) |
| 53 | + } |
| 54 | + } |
| 55 | + return true |
| 56 | + } |
| 57 | + |
| 58 | + for (node in graph.indices) { |
| 59 | + if (!bfs(node)) return false |
| 60 | + } |
| 61 | + |
| 62 | + return true |
| 63 | + } |
| 64 | + |
| 65 | + private enum class Color { RED, GREEN } |
| 66 | + |
| 67 | + private val Color.inverse |
| 68 | + get() = when (this) { |
| 69 | + Color.RED -> Color.GREEN |
| 70 | + Color.GREEN -> Color.RED |
| 71 | + } |
| 72 | +} |
0 commit comments