|
| 1 | +# There are n couples sitting in 2n seats arranged in a row and want to hold hands. |
| 2 | +# |
| 3 | +# The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. |
| 4 | +# The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), |
| 5 | +# and so on with the last couple being (2n - 2, 2n - 1). |
| 6 | +# |
| 7 | +# Return the minimum number of swaps so that every couple is sitting side by side. |
| 8 | +# A swap consists of choosing any two people, then they stand up and switch seats. |
| 9 | + |
| 10 | +""" |
| 11 | +>>> Solution().minSwapsCouples([0,3,5,2,1,4]) |
| 12 | +2 |
| 13 | +>>> Solution().minSwapsCouples([0,2,1,3]) |
| 14 | +1 |
| 15 | +>>> Solution().minSwapsCouples([3,2,0,1]) |
| 16 | +0 |
| 17 | +>>> Solution().minSwapsCouples([1,4,0,5,8,7,6,3,2,9]) |
| 18 | +3 |
| 19 | +>>> Solution().minSwapsCouples([2,0,5,4,3,1]) |
| 20 | +1 |
| 21 | +""" |
| 22 | + |
| 23 | +from typing import List |
| 24 | + |
| 25 | + |
| 26 | +class Solution: |
| 27 | + def minSwapsCouples(self, row: List[int]) -> int: |
| 28 | + for i in range(len(row)): |
| 29 | + row[i] = row[i] // 2 |
| 30 | + |
| 31 | + graph = self.createGraph(row) |
| 32 | + visited = [False for _ in range(len(row) // 2)] |
| 33 | + swaps = 0 |
| 34 | + |
| 35 | + for i in range(len(row) // 2): |
| 36 | + if not visited[i]: |
| 37 | + swaps += self.getClusterSize(graph, visited, i) - 1 |
| 38 | + |
| 39 | + return swaps |
| 40 | + |
| 41 | + def getClusterSize(self, graph, visited, i): |
| 42 | + visited[i] = True |
| 43 | + swaps = 1 |
| 44 | + |
| 45 | + for node in graph[i]: |
| 46 | + if not visited[node]: |
| 47 | + swaps += self.getClusterSize(graph, visited, node) |
| 48 | + |
| 49 | + return swaps |
| 50 | + |
| 51 | + def createGraph(self, row): |
| 52 | + graph = {} |
| 53 | + |
| 54 | + for i in range(len(row) // 2): |
| 55 | + graph[i] = set() |
| 56 | + |
| 57 | + for i in range(0, len(row), 2): |
| 58 | + person1 = row[i] |
| 59 | + person2 = row[i + 1] |
| 60 | + |
| 61 | + if person1 == person2: |
| 62 | + continue |
| 63 | + |
| 64 | + graph[person1].add(person2) |
| 65 | + graph[person2].add(person1) |
| 66 | + |
| 67 | + return graph |
0 commit comments