Showing posts with label adjacency list. Show all posts
Showing posts with label adjacency list. Show all posts

Wednesday, September 21, 2016

Frog Jump

A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit.
If the frog's last jump was k units, then its next jump must be either k - 1, k, or k + 1 units. Note that the frog can only jump in the forward direction.
Note:
  • The number of stones is ≥ 2 and is < 1,100.
  • Each stone's position will be a non-negative integer < 231.
  • The first stone's position is always 0.
Example 1:
[0,1,3,5,6,8,12,17]

There are a total of 8 stones.
The first stone at the 0th unit, second stone at the 1st unit,
third stone at the 3rd unit, and so on...
The last stone at the 17th unit.

Return true. The frog can jump to the last stone by jumping 
1 unit to the 2nd stone, then 2 units to the 3rd stone, then 
2 units to the 4th stone, then 3 units to the 6th stone, 
4 units to the 7th stone, and 5 units to the 8th stone.
Example 2:


[0,1,2,3,4,8,9,11]

Return false. There is no way to jump to the last stone as 
the gap between the 5th and 6th stone is too large.
Analysis
With possible movements defined as constrains/rules, and target is to find if something is reachable, a natural thought would be finding if there's a path between two nodes in a graph. So adjacency list is a good candidate data structure to use. Controversy to traditional use of adjacency list, which is built up to represent a graph before traverse it, this algorithm built it up on the fly and used it as a memoization mechanism to avoid duplicate computations.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class Solution {
    public boolean canCross(int[] stones) {
        Objects.requireNonNull(stones);
   if(stones.length==1)return true;//one stone means the one to the other side
   if(stones.length==2) return (stones[1]==1?true:false);
   //this is an adjacency list. and our target is to figure out 
   //if there's a path to a node following certain restrictions
   //Controversy to traditional use of adjacency list, this list is built up on the fly
        Map<Integer, Set<Integer>> validMovements = new HashMap<Integer, Set<Integer>>();
        for(int i:stones){
         validMovements.put(i, new HashSet<Integer>());
        }
        validMovements.get(0).add(1);
        return dfs(validMovements,1,1,stones[stones.length-1]);
  }
  private boolean dfs(Map<Integer, Set<Integer>> validPositions, int curPosition, int lastJumpUnits, int endPosition){
   boolean reachable = false;
   for(int i=-1;i<=1;i++){
    int nextPosition = curPosition + lastJumpUnits+i;
    if(nextPosition==endPosition){
     return true;
    }
    //lastJumpUnits+i=0, not jumping, will make infinite loop so to avoid it
    if(lastJumpUnits+i>0 && validPositions.containsKey(nextPosition) 
      && !validPositions.get(nextPosition).contains(lastJumpUnits+i)){
     //we go here only when nextPosition is valid and nextPosition's movement has not been done
     //validPositions.get(nextPosition).add(lastJumpUnits+i);
     reachable = dfs(validPositions,nextPosition,lastJumpUnits+i,endPosition);
     if(reachable)break;
    }
   }
   validPositions.get(curPosition).add(lastJumpUnits);
   return reachable;
  }
}

Wednesday, June 08, 2016

Reconstruct Itinerary

Reconstruct Itinerary

Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
Note:
  1. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
  2. All airports are represented by three capital letters (IATA code).
  3. You may assume all tickets may form at least one valid itinerary.
Example 1:
tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Return ["JFK", "MUC", "LHR", "SFO", "SJC"].
Example 2:
tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Return ["JFK","ATL","JFK","SFO","ATL","SFO"].
Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package array;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;

public class ResonstructIternenary {
 public List<String> findItinerary(String[][] tickets) {
  // construct adjacency list, make its adjacency list sorted
  // make sure it is really a list and not set. use set when it does not allow
  // duplication 
  //sorted list in java can be priority queue
  Map<String, PriorityQueue<String>> adl = new HashMap<String, PriorityQueue<String>>();
  for (String[] ft : tickets) {
   PriorityQueue<String> to = adl.get(ft[0]);
   if (to == null)
    to = new PriorityQueue<String>();// so every from node has a
             // queue even it is empty
   to.add(ft[1]);
   adl.put(ft[0], to);
  }
  //to hold the path
  LinkedList<String> itinerary = new LinkedList<String>();

  dfs(adl, "JFK", itinerary);
  return itinerary;
 }

 /**
  * depth first traversal following the minimum ordered destinations 
  * remove the destination from adjacency list so that it won't be visited twice 
  * when no further destination to go further, put the destination to the path
  *  
  * @param adl
  * @param string
  * @param itinerary
  */
 private void dfs(Map<String, PriorityQueue<String>> adl, String from,
   LinkedList<String> itinerary) {
  while (adl.keySet().contains(from) && adl.get(from).size() > 0) {
   dfs(adl, adl.get(from).poll(), itinerary);
  }
  // it will reach to here after dfs is done, which means reaching to
  // deepest leaves from current node
  // the stack of nested calls keeps the order of node visiting. reflect
  // it by adding to from of list
  itinerary.addFirst(from);
 }

 public static void main(String[] args) {
  ResonstructIternenary o = new ResonstructIternenary();
  String[][] tickets = { { "JFK", "SFO" }, { "JFK", "ATL" },
    { "SFO", "JFK" } };
  List<String> itinerary = o.findItinerary(tickets);
  System.out.println(itinerary);
 }
}