code: public static void apply(MutableFst fst) {
      fst.throwIfInvalid();
  
      IntOpenHashSet accessible = new IntOpenHashSet(fst.getStateCount());
      IntOpenHashSet coaccessible = new IntOpenHashSet(fst.getStateCount());
      dfsForward(fst.getStartState(), accessible);
      int numStates = fst.getStateCount();
      for (int i = 0; i < numStates; i++) {
        MutableState s = fst.getState(i);
        if (fst.getSemiring().isNotZero(s.getFinalWeight())) {
          dfsBackward(s, coaccessible);
        }
      }
  
      if (accessible.size() == fst.getStateCount() && coaccessible.size() == fst.getStateCount()) {
        // common case, optimization bail early
        return;
      }
  
      ArrayList<MutableState> toDelete = new ArrayList<>();
      int startId = fst.getStartState().getId();
      for (int i = 0; i < numStates; i++) {
        MutableState s = fst.getState(i);
        if (s.getId() == startId) {
          continue; // cant delete the start state
        }
        if (!accessible.contains(s.getId()) || !coaccessible.contains(s.getId())) {
          toDelete.add(s);
        }
      }
      fst.deleteStates(toDelete);
    }
docs: Trims an Fst, removing states and arcs that are not on successful paths.
  
  @param fst the fst to trim