/* * Return true if there is a path from cur to target. */ booleanDFS(Node cur, Node target, Set<Node> visited){ returntrueif cur is target; for (next : each neighbor of cur) { if (next is not in visited) { add next to visted; returntrueifDFS(next, target, visited)== true; } } returnfalse; }
/** * Return the length of the shortest path between root and target node. */ intBFS(Node root, Node target){ Queue<Node> queue; // store all nodes which are waiting to be processed Set<Node> used; // store all the used nodes int step = 0; // number of steps neeeded from root to current node // initialize add root to queue; add root to used; // BFS while (queue is not empty) { step = step + 1; // iterate the nodes which are already in the queue int size = queue.size(); for (int i = 0; i < size; ++i) { Node cur = the first node in queue; return step if cur is target; for (Node next : the neighbors of cur) { if (next is not in used) { add next to queue; add next to used; } } remove the first node from queue; } } return -1; // there is no path from root to target }
1.3 最大公约数、最小公倍数
1 2 3
publicintgcd(int x, int y){ return y > 0 ? gcd(y, x % y) : x; }
1.4 二分查找
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicintbinarySearch(int[] nums, int target){ int low, high, mid;