def bfs(self, S, T, player): # initialize BFS parent = [[None for _ in range(self.size)] for _ in range(self.size)] Q = Queue() for s in S: Q.add(s) parent[s[0]][s[1]] = -1 # BFS loop cnt = 0 while len(Q) > 0: cnt += 1 r, c = Q.remove() for d in DIR: rr = r + d[0] cc = c + d[1] if 0 <= rr and rr < self.size and 0 <= cc and cc < self.size and parent[ rr][cc] == None and self.is_controlled_by( rr, cc, player): Q.add((rr, cc)) parent[rr][cc] = (r, c) # check whether the other side was reached for r, c in T: if parent[r][c] != None: # build the path path = [] cur = (r, c) while cur != -1: path.append(cur) cur = parent[cur[0]][cur[1]] return path return None
def myBfs(self, S, direction, player, state): # initialize BFS minDistanceFromGoal = state.size + 1 parent = [[None for _ in range(state.size)] for _ in range(state.size)] Q = Queue() for s in S: Q.add(s) parent[s[0]][s[1]] = -1 # BFS loop cnt = 0 while len(Q) > 0: cnt += 1 r, c = Q.remove() for d in tak.DIR: rr = r + d[0] cc = c + d[1] if 0 <= rr < state.size and 0 <= cc < state.size and \ parent[rr][cc] is None and state.is_controlled_by(rr, cc, player): Q.add((rr, cc)) minDistanceFromGoal = min( self.check_possible_path_from_stack( direction, r, c, state, player), minDistanceFromGoal) parent[rr][cc] = (r, c) # check whether the other side was reached r, c, step, reverse = self.getDirectionIndexes(direction, state) for i in range(0, state.size): # maxListOfPath = [] # list of paths maxList = [] # list of coordinates of the subpaths iterationList = range(0, state.size) listOfDistancesFromGoal = [] if reversed: reversed(iterationList) goalPosition = iterationList[0] if r == -1: for row in iterationList: if parent[row][c] is not None: # build the path cur = (row, c) # maxListOfPath.append(self.buildPath(parent, cur)) maxList.append(cur) listOfDistancesFromGoal.append(abs(goalPosition - row)) else: # column for col in iterationList: if parent[r][col] is not None: # build the path cur = (r, col) # maxListOfPath.append(self.buildPath(parent, cur)) maxList.append(cur) listOfDistancesFromGoal.append(abs(goalPosition - col)) if len(maxList) == 1: return listOfDistancesFromGoal[0], minDistanceFromGoal elif len(maxList) > 1: return listOfDistancesFromGoal[self.findFarthestFromCapstone( maxList, state)], minDistanceFromGoal r += step[0] c += step[1] return state.size, minDistanceFromGoal