| 23 | 31 | second being a set of coordinates, representing |
| 24 | 32 | the owner's territories. |
| 25 | 33 | """ |
| 26 | | pass |
| 34 | # Edge Case: Invalid coordinates outside board boundaries |
| 35 | if x < 0 or x >= self.cols or y < 0 or y >= self.rows: |
| 36 | raise ValueError('Invalid coordinate') |
| 37 | |
| 38 | # Edge Case: Coordinate is not an empty intersection |
| 39 | if self.board[y][x] != ' ': |
| 40 | return ('', set()) |
| 41 | |
| 42 | visited = set() |
| 43 | territory_coords = set() |
| 44 | owners = set() |
| 45 | |
| 46 | def dfs(cx, cy): |
| 47 | # Edge Case: Out of bounds |
| 48 | if cx < 0 or cx >= self.cols or cy < 0 or cy >= self.rows: |
| 49 | return |
| 50 | |
| 51 | # Edge Case: Already visited |
| 52 | if (cx, cy) in visited: |
| 53 | return |
| 54 | |
| 55 | visited.add((cx, cy)) |
| 56 | |
| 57 | # Edge Case: Hit a stone |
| 58 | if self.board[cy][cx] in 'WB': |
| 59 | owners.add(self.board[cy][cx]) |
| 60 | return |
| 61 | |
| 62 | # Edge Case: Empty intersection - add to territory |
| 63 | if self.board[cy][cx] == ' ': |
| 64 | territory_coords.add((cx, cy)) |
| 65 | # Explore neighbors |
| 66 | dfs(cx+1, cy) |
| 67 | dfs(cx-1, cy) |
| 68 | dfs(cx, cy+1) |
| 69 | dfs(cx, cy-1) |
| 70 | |
| 71 | dfs(x, y) |
| 72 | |
| 73 | # Edge Case: Territory touches edges or has no owners |
| 74 | if len(owners) == 0: |
| 75 | owner = '' |
| 76 | elif len(owners) == 1: |
| 77 | owner = list(owners)[0] |
| 78 | else: |
| 79 | owner = '' |
| 80 | |
| 81 | return (owner, territory_coords) |
| 27 | 82 | |
| 28 | 83 | def territories(self): |
| 29 | 84 | """Find the owners and the territories of the whole board |
| 36 | 91 | , i.e. "W", "B", "". The value being a set |
| 37 | 92 | of coordinates owned by the owner. |
| 38 | 93 | """ |
| 39 | | pass |
| 94 | result = {'W': set(), 'B': set(), '': set()} |
| 95 | visited = set() |
| 96 | |
| 97 | # Edge Case: Empty board |
| 98 | if self.rows == 0 or self.cols == 0: |
| 99 | return result |
| 100 | |
| 101 | for y in range(self.rows): |
| 102 | for x in range(self.cols): |
| 103 | # Edge Case: Only process empty intersections that haven't been visited |
| 104 | if self.board[y][x] == ' ' and (x, y) not in visited: |
| 105 | owner, territory_coords = self.territory(x, y) |
| 106 | result[owner].update(territory_coords) |
| 107 | visited.update(territory_coords) |
| 108 | |
| 109 | return result |
| 110 | # Handled Edge Cases: Invalid coordinates outside board boundaries, Coordinate is not an empty intersection, Out of bounds during DFS, Already visited coordinates, Hit a stone during exploration, Empty intersection territory, Territory touches edges or has no owners, Empty board, Only process unvisited empty intersections |