|
| 1 | +packagekotlin |
| 2 | + |
| 3 | +importjava.util.* |
| 4 | + |
| 5 | +classSolution { |
| 6 | +funisBipartiteDfs(graph:Array<IntArray>):Boolean { |
| 7 | +if (graph.isEmpty())returntrue |
| 8 | + |
| 9 | +val nodeColorMap= mutableMapOf<Int,Color>() |
| 10 | +fundfs(node:Int,defaultColor:Color):Boolean { |
| 11 | +if (node!in nodeColorMap.keys) nodeColorMap[node]= defaultColor |
| 12 | +for (adjacentNodein 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)returnfalse |
| 18 | +elsecontinue |
| 19 | + } |
| 20 | +if (!dfs(adjacentNode, defaultColor.inverse))returnfalse |
| 21 | + } |
| 22 | +returntrue |
| 23 | + } |
| 24 | + |
| 25 | +for (nodein graph.indices) { |
| 26 | +if (nodein nodeColorMap.keys)continue |
| 27 | +if (!dfs(node,Color.RED))returnfalse |
| 28 | + } |
| 29 | +returntrue |
| 30 | + } |
| 31 | + |
| 32 | +funisBipartiteBfs(graph:Array<IntArray>):Boolean { |
| 33 | +if (graph.isEmpty())returntrue |
| 34 | +val nodeColorMap= mutableMapOf<Int,Color>() |
| 35 | + |
| 36 | +funbfs(startNode:Int):Boolean { |
| 37 | +// if the node is already colored, return true |
| 38 | +if (startNodein nodeColorMap.keys)returntrue |
| 39 | + nodeColorMap[startNode]=Color.RED |
| 40 | + |
| 41 | +val queue= (LinkedList<Int>()asQueue<Int>).apply { add(startNode) } |
| 42 | +while (queue.isNotEmpty()) { |
| 43 | +val currentNode= queue.remove() |
| 44 | +val colorOfCurrentNode= nodeColorMap.getValue(currentNode) |
| 45 | +for (adjacentNodein graph[currentNode]) { |
| 46 | +if (adjacentNodein nodeColorMap.keys) { |
| 47 | +val colorOfAdjacentNode= nodeColorMap.getValue(adjacentNode) |
| 48 | +if (colorOfAdjacentNode== colorOfCurrentNode)returnfalse |
| 49 | +continue |
| 50 | + } |
| 51 | + nodeColorMap[adjacentNode]= colorOfCurrentNode.inverse |
| 52 | + queue.add(adjacentNode) |
| 53 | + } |
| 54 | + } |
| 55 | +returntrue |
| 56 | + } |
| 57 | + |
| 58 | +for (nodein graph.indices) { |
| 59 | +if (!bfs(node))returnfalse |
| 60 | + } |
| 61 | + |
| 62 | +returntrue |
| 63 | + } |
| 64 | + |
| 65 | +privateenumclassColor {RED,GREEN } |
| 66 | + |
| 67 | +privatevalColor.inverse |
| 68 | + get()=when (this) { |
| 69 | +Color.RED->Color.GREEN |
| 70 | +Color.GREEN->Color.RED |
| 71 | + } |
| 72 | +} |