public static List<List<Integer>> levelOrderBottom(TreeNode root) { if (root == null) { return new ArrayList<>(); } List<List<Integer>> res = new ArrayList<>(); List<Integer> level = new ArrayList<>(); Queue<TreeNode> queue = new LinkedList<>(); // 新建一个queue,用来记录哪些nodes是目前的波前 queue.add(root); // 向root注水作为波前 queue.add(null); // 在波前队列queue加null作为Flag代表这层level已访问结束 while (queue.size() != 0) { TreeNode u = queue.poll(); if (u != null) { level.add(u.val); /* * 波前u向其所有有连同的node扩散 * u是v的predecessor前驱 or parent * v是u的 descendent后记 * */ if (u.left != null) { queue.add(u.left); } if (u.right != null) { queue.add(u.right); } } else { res.add(level); level = new ArrayList<Integer>(); if (!queue.isEmpty()) { queue.add(null); } } } Collections.reverse(res); return res; }
/** * put the flip lake tile of the game * * @param players list of players */ private void setUpLakeTile(Queue<Player> players) { Random r = new Random(); int randomRedLantern = r.nextInt(players.size()); Queue<Color> color = startLakeTile.getColorOfFourSides(); // change the current player who get red lantern card color.add(color.remove()); for (int i = 0; i < randomRedLantern; i++) { players.add(players.remove()); } int current_number_player = 0; // add index to player for (int i = 0; i < players.size(); i++) { Player p = players.remove(); p.setIndex(i); players.add(p); } for (Color lantern_color : color) { if (current_number_player == players.size()) { break; } else { current_number_player++; } Player p = players.remove(); p.getLanternCards().add(supply.get(lantern_color).pop()); players.add(p); } }
// Returns a code tree that is optimal for these frequencies. Always contains at least 2 symbols, // to avoid degenerate trees. public CodeTree buildCodeTree() { // Note that if two nodes have the same frequency, then the tie is broken by which tree contains // the lowest symbol. Thus the algorithm is not dependent on how the queue breaks ties. Queue<NodeWithFrequency> pqueue = new PriorityQueue<NodeWithFrequency>(); // Add leaves for symbols with non-zero frequency for (int i = 0; i < frequencies.length; i++) { if (frequencies[i] > 0) pqueue.add(new NodeWithFrequency(new Leaf(i), i, frequencies[i])); } // Pad with zero-frequency symbols until queue has at least 2 items for (int i = 0; i < frequencies.length && pqueue.size() < 2; i++) { if (i >= frequencies.length || frequencies[i] == 0) pqueue.add(new NodeWithFrequency(new Leaf(i), i, 0)); } if (pqueue.size() < 2) throw new AssertionError(); // Repeatedly tie together two nodes with the lowest frequency while (pqueue.size() > 1) { NodeWithFrequency nf1 = pqueue.remove(); NodeWithFrequency nf2 = pqueue.remove(); pqueue.add( new NodeWithFrequency( new InternalNode(nf1.node, nf2.node), Math.min(nf1.lowestSymbol, nf2.lowestSymbol), nf1.frequency + nf2.frequency)); } // Return the remaining node return new CodeTree((InternalNode) pqueue.remove().node, frequencies.length); }
private void adjustIncomingPosition(Queue<PositionElement> longs, Queue<PositionElement> shorts) { if (mIncomingPosition.signum() == 1) { longs.add(new PositionElement(mIncomingPosition, mClosingPrice)); } else if (mIncomingPosition.signum() == -1) { shorts.add(new PositionElement(mIncomingPosition.negate(), mClosingPrice)); } }
private Map<String, File> getAllClasses(String rootDir) { File[] arr = new File(rootDir).listFiles(); Queue<File> toNavigate = new LinkedList<File>(); Queue<String> toNavigateString = new LinkedList<String>(); Map<String, File> classMap = new HashMap<String, File>(); for (File f : arr) { toNavigate.add(f); toNavigateString.add(""); } while (!toNavigate.isEmpty()) { File next = toNavigate.poll(); String nextString = toNavigateString.poll(); if (next.isDirectory()) { arr = next.listFiles(); for (File f : arr) { toNavigate.add(f); toNavigateString.add(nextString + next.getName() + "."); } } else { if (next.getName().endsWith(".class")) { System.out.println(nextString + next.getName().substring(0, next.getName().length() - 6)); classMap.put(nextString + next.getName().substring(0, next.getName().length() - 6), next); } } } return classMap; }
/** * Locate each unexpanded Structure|Sequence and: 1. check that none of its fields is referenced * => do not expand 2. add all of its fields as leaves Note that #2 may end up adding additional * leaf structs &/or seqs */ public void expand() { // Create a queue of unprocessed leaf compounds Queue<DapVariable> queue = new ArrayDeque<DapVariable>(); for (int i = 0; i < variables.size(); i++) { DapVariable var = variables.get(i); if (!var.isTopLevel()) continue; // prime the queue if (var.getSort() == DapSort.STRUCTURE || var.getSort() == DapSort.SEQUENCE) { DapStructure struct = (DapStructure) var; // remember Sequence subclass Structure if (expansionCount(struct) == 0) queue.add(var); } } // Process the queue in prefix order while (queue.size() > 0) { DapVariable vvstruct = queue.remove(); DapStructure dstruct = (DapStructure) vvstruct; for (DapVariable field : dstruct.getFields()) { if (findVariableIndex(field) < 0) { // Add field as leaf this.segments.add(new Segment(field)); this.variables.add(field); } if (field.getSort() == DapSort.STRUCTURE || field.getSort() == DapSort.SEQUENCE) { if (expansionCount((DapStructure) field) == 0) queue.add(field); } } } this.expansion = Expand.EXPANDED; }
static long maxFlow() { long totalFlow = 0; while (true) { Queue<Integer> q = new LinkedList<>(); int[] parent = new int[cap.length]; Arrays.fill(parent, -1); q.add(s); while (!q.isEmpty()) { int node = q.poll(); for (int j = 1; j <= n; j++) { if (cap[node][j] - flow[node][j] > 0 && parent[j] == -1) { parent[j] = node; q.add(j); } } } if (parent[t] == -1) break; long cflow = Long.MAX_VALUE; int current = t; while (current != s) { cflow = Math.min(cflow, cap[parent[current]][current] - flow[parent[current]][current]); current = parent[current]; } current = t; while (current != s) { flow[parent[current]][current] += cflow; flow[current][parent[current]] -= cflow; current = parent[current]; } totalFlow += cflow; } return totalFlow; }
/* Creates tree by mapping the array left to right, top to bottom. */ public static TreeNode createTreeFromArray(int[] array) { if (array.length > 0) { TreeNode root = new TreeNode(array[0]); java.util.Queue<TreeNode> queue = new java.util.LinkedList<TreeNode>(); queue.add(root); boolean done = false; int i = 1; while (!done) { TreeNode r = (TreeNode) queue.element(); if (r.left == null) { r.left = new TreeNode(array[i]); i++; queue.add(r.left); } else if (r.right == null) { r.right = new TreeNode(array[i]); i++; queue.add(r.right); } else { queue.remove(); } if (i == array.length) done = true; } return root; } else { return null; } }
// Minimize the distance in k sorted arrays public static int p15(int[][] arrs) { Queue<P15Obj> q = new PriorityQueue<P15Obj>(); int max = Integer.MIN_VALUE; for (int i = 0; i < arrs.length; i++) { if (arrs[i].length > 0) { q.add(new P15Obj(i, 0, arrs[i][0])); if (max < arrs[i][0]) { max = arrs[i][0]; } } else { return -1; } } int minDist = Integer.MAX_VALUE; do { P15Obj min = q.remove(); minDist = Math.min(max - min.val, minDist); int newVal = arrs[min.i][min.j + 1]; if (newVal > max) max = newVal; q.add(new P15Obj(min.i, min.j + 1, newVal)); } while (q.peek().j < arrs[q.peek().i].length - 1); return minDist; }
// Algorithm to randomly shuffle the elements of a message. final Message shuffle(Message message) throws FormatException { Message shuffled = messages.make(); // Read all elements of the packet and insert them in a Queue. Queue<String> old = new LinkedList<>(); int N = 0; while (!message.isEmpty()) { old.add(message.readString()); message = message.rest(); N++; } // Then successively and randomly select which one will be inserted until none remain. for (int i = N; i > 0; i--) { // Get a random number between 0 and N - 1 inclusive. int n = crypto.getRandom(i - 1); for (int j = 0; j < n; j++) { old.add(old.remove()); } // add the randomly selected element to the queue. shuffled = shuffled.attach(old.remove()); } return shuffled; }
@Override public void buildRecursiveCountInfo() throws WikitException { if (!hasConceptRelationCreated()) { throw new WikitException("Category-concept relation hasn't created."); } Collection<Integer> leafIds = getLeafCategoryIds(); ProgressCounter progress = new ProgressCounter(); progress.setMaxCount(leafIds.size()); for (int catId : leafIds) { int cptCount = getConceptCount(catId); incRecursiveConceptCount(catId, cptCount); // visit all ancestor node, and inc recursive concept count Queue<Integer> queue = new LinkedList<>(); queue.add(catId); while (!queue.isEmpty()) { int childId = queue.poll(); Set<Integer> parentIds = getParentIds(childId); for (int pid : parentIds) { incRecursiveConceptCount(pid, cptCount); queue.add(pid); } } progress.increment(); } String key = (prefix + "cnf"); jedis.hset(key, "assignRecursiveCount", "created"); progress.done(); }
@Override public void buildEdgeRelation(CategoryCache categoryCache) throws WikitException { if (!categoryCache.hasDone()) { throw new WikitException("Please create category cache first."); } String[] skippedCategories = new String[] {"跨学科领域", "总类", "词汇列表"}; Set<Integer> skippedCatIds = new HashSet<>(); for (String c : skippedCategories) { skippedCatIds.add(categoryCache.getIdByName(c)); } ProgressCounter counter = new ProgressCounter(); try { String root = conf.getWikiRootCategoryName(); int id = categoryCache.getIdByName(root); this.saveNameIdMapping(root, id); this.rootId = id; this.saveDepth(id, 0); Queue<Integer> queue = new LinkedList<>(); queue.add(id); while (!queue.isEmpty()) { int pid = queue.poll(); int depth = this.getDepth(pid); Set<Integer> childIds = categoryCache.getChildIds(pid); for (Integer childId : childIds) { if (skippedCatIds.contains(childId)) { continue; } int childDepth = categoryCache.getDepth(childId, -1); if (childDepth != (depth + 1)) { continue; // skip } if (!idExist(childId)) { String name = categoryCache.getNameById(childId); this.saveNameIdMapping(name, childId); this.saveDepth(childId, depth + 1); queue.add(childId); } this.saveParents(childId, pid); this.saveChildren(pid, childId); } counter.increment(); } this.finishNameIdMapping(); this.edgeRelationCreated(); } catch (MissedException e) { LOG.error(e.toString()); throw new WikitException(e); } counter.done(); LOG.info("Edge relation has created."); }
public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> results = new LinkedList<List<Integer>>(); Queue<TreeNode> currentLevel = new LinkedList<TreeNode>(); Queue<TreeNode> nextLevel = new LinkedList<TreeNode>(); if (root == null) { return results; } else { currentLevel.add(root); } List<Integer> tmp = new LinkedList<Integer>(); while (!currentLevel.isEmpty()) { TreeNode node = currentLevel.remove(); if (node != null) { tmp.add(node.val); nextLevel.add(node.left); nextLevel.add(node.right); } if (currentLevel.isEmpty()) { if (!tmp.isEmpty()) { results.add(0, tmp); } tmp = new LinkedList<Integer>(); currentLevel = nextLevel; nextLevel = new LinkedList<TreeNode>(); } } return results; }
/** * Returns an array of strings naming the files and directories in the directory denoted by this * abstract pathname, and all of its subdirectories. * * <p>If this abstract pathname does not denote a directory, then this method returns {@code * null}. Otherwise an array of strings is returned, one for each file or directory in the * directory and its subdirectories. Names denoting the directory itself and the directory's * parent directory are not included in the result. Each string is a path relative to the given * directory. * * <p>There is no guarantee that the name strings in the resulting array will appear in any * specific order; they are not, in particular, guaranteed to appear in alphabetical order. * * @param path the abstract pathname to list * @return An array of strings naming the files and directories in the directory denoted by this * abstract pathname and its subdirectories. The array will be empty if the directory is * empty. Returns {@code null} if this abstract pathname does not denote a directory. * @throws IOException if a non-Alluxio error occurs */ public String[] listRecursive(String path) throws IOException { // Clean the path by creating a URI and turning it back to a string AlluxioURI uri = new AlluxioURI(path); path = uri.toString(); List<String> returnPaths = new ArrayList<>(); Queue<String> pathsToProcess = new ArrayDeque<>(); // We call list initially, so we can return null if the path doesn't denote a directory String[] subpaths = list(path); if (subpaths == null) { return null; } else { for (String subp : subpaths) { pathsToProcess.add(PathUtils.concatPath(path, subp)); } } while (!pathsToProcess.isEmpty()) { String p = pathsToProcess.remove(); returnPaths.add(p.substring(path.length() + 1)); // Add all of its subpaths subpaths = list(p); if (subpaths != null) { for (String subp : subpaths) { pathsToProcess.add(PathUtils.concatPath(p, subp)); } } } return returnPaths.toArray(new String[returnPaths.size()]); }
static int maxFlow() { int mf = 0; while (true) { Queue<Integer> q = new LinkedList<Integer>(); p = new int[V]; Arrays.fill(p, -1); p[0] = 0; q.add(0); while (!q.isEmpty()) { int u = q.remove(); if (u == 1) break; for (int i = 0; i < adjList[u].size(); ++i) { int v = adjList[u].get(i); if (p[v] == -1 && res[u][v] > 0) { p[v] = u; q.add(v); } } } if (p[1] == -1) break; augment(1); ++mf; } return mf; }
// pathing private List<Room> path(Room start, Room destination, Set<Room> travelable) { Queue<Room> frontier = new LinkedList<Room>(); frontier.add(start); Map<Room, Room> visited = new HashMap<Room, Room>(); visited.put(start, null); while (!frontier.isEmpty()) { Room current = frontier.poll(); System.out.println("\n---\n" + frontier + "\n\n" + travelable + "\n---\n"); if ((destination == null && current.visited == false) || current == destination) { List<Room> path = new ArrayList<Room>(); Room next = current; while (visited.get(next) != null) { path.add(0, next); next = visited.get(next); } System.out.println("Returning: " + path); return path; } for (Room next : current.adjacent) { if (!visited.containsKey(next) && travelable.contains(next)) { frontier.add(next); visited.put(next, current); } } } System.out.println("Returning: null"); return null; }
public static Phylogeny generatePerfectTree(int size, boolean randomNames) { Phylogeny tree = new Phylogeny(); int currentTreeSize = 0; Queue<PhylogenyNode> currentLeaves = new LinkedList<>(); PhylogenyNode root = new PhylogenyNode(); tree.setRoot(root); currentLeaves.add(root); currentTreeSize++; while (currentTreeSize < size) { PhylogenyNode currentNode = currentLeaves.poll(); PhylogenyNode child1 = new PhylogenyNode(); PhylogenyNode child2 = new PhylogenyNode(); currentNode.setChild1(child1); currentNode.setChild2(child2); currentLeaves.add(child1); currentLeaves.add(child2); currentTreeSize++; } if (randomNames) renameTreeLeavesRandomly(tree); else renameTreeLeavesLeftToRight(tree); return tree; }
public static void lightChange(Queue<Car> q) { // if light is true, that means the green light is for N and S // This means we must change the cars wait times in E and W Queue<Car> temp = new LinkedList<Car>(); Car tc; while (!q.isEmpty()) { tc = q.remove(); temp.add(tc); } int tnum = 1; q.clear(); // System.out.println("In the light change"); while (!temp.isEmpty()) { Car tcar = temp.remove(); // System.out.println("Light Change: " + tcar.display()); if (tnum == 1) { tcar.setTotalWait(3); tcar.setWaitTime(3); q.add(tcar); } else if (tnum == 2) { tcar.setTotalWait(2); tcar.setWaitTime(2); q.add(tcar); } else { tcar.setTotalWait(1); tcar.setWaitTime(1); q.add(tcar); } tnum++; } }
/** * Using a serialized list of tree nodes to generate a binary tree. There is detail information: * https://leetcode.com/problems/binary-tree-inorder-traversal/ * * @param serializedTreeNode a serialized list of tree nodes * @return the node of tree root */ public static TreeNode generateTree(String serializedTreeNode) { String[] tokens = serializedTreeNode.split(","); if (tokens.length <= 0) return null; TreeNode root = new TreeNode(Integer.parseInt(tokens[0])); Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); int pos = 1; while (pos < tokens.length) { TreeNode temp = queue.remove(); if (!tokens[pos].equals("#")) { TreeNode left = new TreeNode(Integer.parseInt(tokens[pos])); temp.left = left; queue.add(left); } pos++; if (pos >= tokens.length) break; if (!tokens[pos].equals("#")) { TreeNode right = new TreeNode(Integer.parseInt(tokens[pos])); temp.right = right; queue.add(right); } pos++; } return root; }
private static boolean a(Context context, String str) { boolean z = false; synchronized (g) { SharedPreferences j = m.a(context).j(); if (c == null) { String[] split = j.getString("pref_msg_ids", com.xiaomi.e.a.f).split(f.i); c = new LinkedList(); for (Object add : split) { c.add(add); } } if (c.contains(str)) { z = true; } else { c.add(str); if (c.size() > 10) { c.poll(); } String a = d.a(c, f.i); Editor edit = j.edit(); edit.putString("pref_msg_ids", a); edit.commit(); } } return z; }
public static int minDepth(Node root) { Queue<Node> q = new LinkedList<Node>(); q.add(root); System.out.println(root.val); int countLevel = 0; while (!q.isEmpty()) { int level = q.size(); countLevel++; while (level > 0) { Node temp = q.poll(); if (temp.left == null && temp.right == null) { return countLevel; } else { if (temp.left != null) { q.add(temp.left); System.out.print(temp.left.val + " "); } if (temp.right != null) { q.add(temp.right); System.out.print(temp.right.val + " "); } } level--; } System.out.println(""); } return 0; }
/** * breadth first search -- ONLY prints edges in this version * * @param Starting vertex */ public void bfs(String start) { clearAll(); // reset scratches for all Vertices Vertex root = verts.get(start); // get root Vertex root.dist = 0; // set distance to zero if (root == null) // throw exception if root Vertex DNE throw new NoSuchElementException("Start Vertex not found"); Queue<Vertex> queue = new LinkedList<Vertex>(); // create queue queue.add(root); // add root Vertex to queue while (!queue.isEmpty()) { // continue while not empty Vertex tempVertex = queue.poll(); // grab next Vertex from queue tempVertex.scratch = 2; // mark vertex as visited for (int i = 0; i < numVertices; i++) { // search for nodes in tempVetex's row // if an edge exists and dest Vertex is unseen add to queue if ((matrix[tempVertex.vertNumber][i] > 0) && numbers.get(i).scratch == 0) { Vertex neighbor = numbers.get(i); neighbor.dist = tempVertex.dist + 1; // set distance neighbor.prev = tempVertex; // set previous Vertex neighbor.scratch = 1; // mark as seen queue.add(neighbor); // add to queue // print edge System.out.println( neighbor.prev.name + "->" + neighbor.name + ":" + matrix[neighbor.prev.vertNumber][neighbor.vertNumber]); } } } }
/* Fill the bipartite graph if possible. */ boolean[] solve() { Map<Integer, List<Integer>> gr = makeGraph(); boolean[] truthTable = new boolean[count]; // keep track of which ones we've visited boolean[] visited = new boolean[count]; Queue<Integer> queue = new LinkedList<Integer>(); truthTable[0] = true; // assume the first person tells the truth queue.add(0); // Breadth first search on graph while (!queue.isEmpty()) { int next = queue.remove(); boolean truth = truthTable[next]; List<Integer> list = gr.get(next); // Go through list and toggle when needed for (int i = 0; i < list.size(); i++) { int node = list.get(i); if (!visited[node]) { visited[node] = true; truthTable[node] = !truth; queue.add(node); } } } return truthTable; }
/** * Creates a new Game instance* * * @param p1Id the id of the first player * @param p2Id the id of the second player * @return a new game instance */ private IGame createGame(String p1Id, String p2Id) { String gid = UUID.randomUUID().toString(); ArrayList<Integer> shuffleArray = new ArrayList<>(); for (int i = 0; i < 52; i++) { shuffleArray.add(i); } Collections.shuffle(shuffleArray); int split = shuffleArray.size() / 2; Queue<Integer> player1Cards = new LinkedList<>(); for (int i = 0; i < split; i++) { player1Cards.add(shuffleArray.get(i)); } Queue<Integer> player2Cards = new LinkedList<>(); for (int i = split; i < shuffleArray.size(); i++) { player2Cards.add(shuffleArray.get(i)); } Game game = new Game(gid, p1Id, p2Id, player1Cards, player2Cards); games.put(gid, game); return game; }
private static void traverse(BinaryTreeNode node) { if (node == null) return; Queue<BinaryTreeNode> queue = new LinkedList<BinaryTreeNode>(); Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>(); queue.add(node); queue.add(null); while (!queue.isEmpty()) { node = queue.poll(); stack.push(node); if (node == null) { if (!queue.isEmpty()) queue.add(null); } else { if (node.getRightNode() != null) queue.add(node.getRightNode()); if (node.getLeftNode() != null) queue.add(node.getLeftNode()); } } while (!stack.isEmpty()) { BinaryTreeNode btNode = stack.pop(); if (btNode != null) { System.out.print(btNode.getData() + " "); } else { System.out.println(" "); } } }
// 思路,还是一样借助两个队列来进行完成 public void connect(TreeLinkNode root) { if (root == null) { return; } Queue<TreeLinkNode> q1 = new LinkedList<TreeLinkNode>(); Queue<TreeLinkNode> q2 = new LinkedList<TreeLinkNode>(); q1.add(root); root.next = null; while (!(q1.isEmpty() && q2.isEmpty())) { while (!q1.isEmpty()) { TreeLinkNode node = q1.poll(); if (node.left != null) { q2.add(node.left); } if (node.right != null) { q2.add(node.right); } } while (!q2.isEmpty()) { TreeLinkNode node = q2.poll(); if (q2.isEmpty()) { node.next = null; } else { node.next = q2.peek(); } q1.add(node); } } }
@Override public String[] findFiles(final String folderName) { File folder = new File(folderName); if (!folder.exists()) { throw new IllegalArgumentException(); } List<String> foundFiles = new ArrayList<String>(); Queue<File> folders = new LinkedList<File>(); folders.add(folder); while (!folders.isEmpty()) { File currentFolder = folders.remove(); File[] currentFiles = currentFolder.listFiles(); for (File f : currentFiles) { if (f.isDirectory()) { folders.add(f); } else if (f.isFile()) { foundFiles.add(f.getAbsolutePath()); } else { throw new RuntimeException("It isn't file or folder"); } } } return foundFiles.toArray(new String[foundFiles.size()]); }
public static int[][] findMinimumDistanceToNearestZero(int[][] matrix) { // step 1: initialize int totalRow = matrix.length, totalCol = matrix[0].length; int[][] dis = new int[totalRow][totalCol]; boolean[][] vis = new boolean[totalRow][totalCol]; Queue<Position> queue = new LinkedList<Position>(); for (int i = 0; i < totalRow; ++i) { for (int j = 0; j < totalCol; ++j) { if (matrix[i][j] == 0) { dis[i][j] = 0; vis[i][j] = true; queue.add(new Position(i, j, 0)); } } } // step 2: BFS while (!queue.isEmpty()) { Position pos = queue.poll(); for (int i = 0; i < 4; ++i) { int nr = pos.row + MOVE[i][0], nc = pos.col + MOVE[i][1]; if (nr < 0 || nr >= totalRow || nc < 0 || nc >= totalCol) continue; if (vis[nr][nc]) continue; dis[nr][nc] = pos.dis + 1; vis[nr][nc] = true; queue.add(new Position(nr, nc, dis[nr][nc])); } } return dis; }
@Override protected AbstractPlanNode recursivelyApply(AbstractPlanNode planNode) { assert (planNode != null); // breadth first: // find AggregatePlanNode with exactly one child // where that child is an AbstractScanPlanNode. // Inline any qualifying AggregatePlanNode to its AbstractScanPlanNode. Queue<AbstractPlanNode> children = new LinkedList<AbstractPlanNode>(); children.add(planNode); while (!children.isEmpty()) { AbstractPlanNode plan = children.remove(); AbstractPlanNode newPlan = inlineAggregationApply(plan); if (newPlan != plan) { if (plan == planNode) { planNode = newPlan; } else { planNode.replaceChild(plan, newPlan); } } for (int i = 0; i < newPlan.getChildCount(); i++) { children.add(newPlan.getChild(i)); } } return planNode; }
int[] nextPillBFS(Node start) { ArrayList<Node> alreadyVisited = new ArrayList<Node>(); Queue<Node> nextToVisit = new LinkedList<Node>(); Queue<Tuple> startDirection = new LinkedList<Tuple>(); ArrayList<Edge> firstDirections = start.getEdges(); for (int i = 0; i < firstDirections.size(); i++) { Node nextFieldToVisit = firstDirections.get(i).end; nextToVisit.add(nextFieldToVisit); startDirection.add(new Tuple(nextFieldToVisit.x - start.x, nextFieldToVisit.y - start.y)); } Node lastTouched; Tuple beginningDirection; while (true) { if (nextToVisit.size() == 0) return new int[] {0, 0}; lastTouched = nextToVisit.remove(); beginningDirection = startDirection.remove(); if (alreadyVisited.contains(lastTouched)) continue; if (lastTouched.hasPill()) { break; } alreadyVisited.add(lastTouched); ArrayList<Edge> neighbourEdges = lastTouched.getEdges(); for (int i = 0; i < neighbourEdges.size(); i++) { nextToVisit.add(neighbourEdges.get(i).end); startDirection.add(beginningDirection); } } return new int[] {beginningDirection.x, beginningDirection.y}; }