Python bidirectional BFS accepted
Python seems to be too slow unless BFS is bothways. \n\n\nclass Solution:\n  def processQueue(self, queue, selfVisited, targetVisited):\n    for _ in range(len(
Python seems to be too slow unless BFS is bothways. \n\n```\nclass Solution:\n  def processQueue(self, queue, selfVisited, targetVisited):\n    for _ in range(len(queue)):\n        cr, cc = queue.popleft()\n        if (cr, cc) in targetVisited:\n          return True\n\n        for d in self.dir:\n          nr, nc = cr + d[0], cc + d[1]\n          if nr >= self.R or nc >= self.C or nr < 0 or nc < 0:\n            continue\n          if self.fr[nr][nc] == 0:\n            continue\n          if (nr, nc) in selfVisited:\n            continue\n          queue.append((nr, nc))\n          selfVisited.add((nr,nc))\n        \n    return False\n  \n  def findNext(self, pos, target):\n    beginque= deque()\n    endque= deque()\n    beginque.append(pos)\n    endque.append(target)\n    step = 0\n    visitedFromBegin = set()\n    visitedFromBegin.add(pos)\n    visitedFromEnd = set()\n    visitedFromEnd.add(target)\n\n    while beginque or endque:\n      if self.processQueue(beginque, visitedFromBegin, visitedFromEnd):\n        return step\n      step += 1\n    \n      if self.processQueue(endque, visitedFromEnd, visitedFromBegin):\n        return step\n      step += 1\n          \n    return -1\n\n\n  def cutOffTree(self, forest: List[List[int]]) -> int:\n    self.dir = [(0,1), (1,0), (0,-1), (-1,0)]\n    self.fr = forest\n    self.R = len(forest)\n    self.C = len(forest[0])\n\n    trees = []\n    treePos = dict()\n    for r in range(self.R):\n      for c in range(self.C):\n        if self.fr[r][c] > 0:\n          trees.append(self.fr[r][c])\n          treePos[self.fr[r][c]] = (r,c)\n\n    trees.sort(reverse=True)\n\n    ret = 0\n    pos = (0,0)\n    while trees:\n      nextTree = trees.pop()\n      if nextTree == 1:\n        continue\n      steps = self.findNext(pos, treePos[nextTree])\n      if steps == -1:\n        return -1\n      ret += steps\n      pos = treePos[nextTree]\n\n    return ret\n```
[]