|
| 1 | +class Solution(object): |
| 2 | + def wallsAndGates(self, rooms): |
| 3 | + """ |
| 4 | + :type rooms: List[List[int]] |
| 5 | + :rtype: None Do not return anything, modify rooms in-place instead. |
| 6 | + """ |
| 7 | + gateDistanceGrid = [['-inf' for value in row] for row in rooms] |
| 8 | + for i in rooms: |
| 9 | + for j in rooms[j]: |
| 10 | + if gateDistanceGrid[i][j] is not '-inf': |
| 11 | + continue |
| 12 | + else: |
| 13 | + gateDistanceGrid[i][j] = 'INF' |
| 14 | + gateDistance = self.traverseNode(i, j, rooms, gateDistanceGrid) |
| 15 | + if gateDistance > 0: |
| 16 | + gateDistanceGrid[i][j] = gateDistance |
| 17 | + return gateDistanceGrid |
| 18 | + |
| 19 | + |
| 20 | + |
| 21 | + def traverseNode(self, i, j, rooms, gateDistanceGrid): |
| 22 | + gateDistance = 0 |
| 23 | + nodesToExplore = [[i, j]] # This is a queue, because we are performing BFS |
| 24 | + while nodesToExplore: |
| 25 | + currentNode = nodesToExplore.pop(0) |
| 26 | + i = currentNode[0] |
| 27 | + j = currentNode[1] |
| 28 | + if rooms[i][j] == -1: |
| 29 | + continue |
| 30 | + if rooms[i][j] == 0: |
| 31 | + gateDistance += 1 |
| 32 | + gateDistanceGrid[i][j] = gateDistance |
| 33 | + break |
| 34 | + unvisitedNeighbour = self.getUnvisitedNeighbour(i, j, rooms, gateDistanceGrid) |
| 35 | + for neighbour in unvisitedNeighbour: |
| 36 | + nodesToExplore.append(neighbour) |
| 37 | + return gateDistance |
| 38 | + |
| 39 | + |
| 40 | + |
| 41 | + def getUnvisitedNeighbour(self, i, j, rooms, gateDistanceGrid): |
| 42 | + unvisitedNeighbours = [] |
| 43 | + if i > 0: |
| 44 | + unvisitedNeighbours.append([i - 1, j]) |
| 45 | + if i < len(rooms) - 1: |
| 46 | + unvisitedNeighbours.append([i + 1, j]) |
| 47 | + if j > 0: |
| 48 | + unvisitedNeighbours.append([i, j - 1]) |
| 49 | + if j < len(rooms[0]) - 1: |
| 50 | + unvisitedNeighbours.append([i, j + 1]) |
| 51 | + return unvisitedNeighbours |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | + |
| 56 | +# Driver Code |
| 57 | +sol = Solution() |
| 58 | +gateDistanceGrid = sol.wallsAndGates() |
| 59 | + |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | + |
| 65 | + |
| 66 | + |
0 commit comments