def getBetterNeighbor(self, location, trace=None): """ If (r, c) has a better neighbor, return the neighbor. Otherwise, return the location (r, c). RUNTIME: O(1) :param location: :param trace: :return: """ (r, c) = location best = location if r - 1 >= 0 and self.get((r - 1, c)) > self.get(best): best = (r - 1, c) if r + 1 < self.numRow and self.get((r + 1, c)) > self.get(best): best = (r + 1, c) if c - 1 >= 0 and self.get((r, c - 1)) > self.get(best): best = (r, c - 1) if c + 1 < self.numCol and self.get((r, c + 1)) > self.get(best): best = (r, c + 1) if not trace is None: trace.getBetterNeighbor(location, best) return best
def getBetterNeighbor(self, location, trace=None): """ If (r, c) has a better neighbor, return the neighbor. Otherwise, return the location (r, c). RUNTIME: O(1) """ (r, c) = location best = location if r - 1 >= 0 and self.get((r - 1, c)) > self.get(best): best = (r - 1, c) if c - 1 >= 0 and self.get((r, c - 1)) > self.get(best): best = (r, c - 1) if r + 1 < self.numRow and self.get((r + 1, c)) > self.get(best): best = (r + 1, c) if c + 1 < self.numCol and self.get((r, c + 1)) > self.get(best): best = (r, c + 1) if not trace is None: trace.getBetterNeighbor(location, best) return best