示例#1
0
  /**
   * BFS algorith
   *
   * @param: print boolean if to print node during traversal
   * @return List of nodes in order visited
   */
  public ArrayList<String> bfs(boolean print) {

    ArrayList<String> ops = new ArrayList<>();

    GraphNode v = source;
    ArrayList<GraphNode> Q = new ArrayList<>();
    Q.add(v);
    v.setVisited(true);
    while (Q.size() != 0) {
      v = Q.remove(0);
      if (print) System.out.println(v);
      ops.add(v.toString());
      //      if(checkStoppingCondition(v, getN())) {
      //        return;
      //      }
      List<Integer> edgeTarget = matrix.get(v.getID());
      for (int i = 0; i < edgeTarget.size(); ++i) {
        if (edgeTarget.get(i) == 1) {
          GraphNode w = info.get(i + 1);
          if (!w.getVisited()) {
            Q.add(w);
            w.setVisited(true);
          }
        }
      }
    }
    return ops;
  }
示例#2
0
  /**
   * Recursive DFS algorthm
   *
   * @param matrix Map of lists representing adj matrix
   * @param info Map of nodes representing node info
   * @param v Node source
   * @param n int number of nodes in graph
   * @param: print boolean if to print node during traversal
   * @return List of nodes in order visited
   */
  public ArrayList<String> dfs_rec(
      Map<Integer, List<Integer>> matrix,
      Map<Integer, GraphNode> info,
      GraphNode v,
      Integer n,
      boolean print,
      ArrayList<String> ops) {
    v.setVisited(true);
    if (print) System.out.println(v);
    ops.add(v.toString());

    //        if(checkStoppingCondition(v, getN())) {
    //            return;
    //        }

    List<Integer> edgeTarget = matrix.get(v.getID());

    for (int i = 0; i < edgeTarget.size(); ++i) {
      if (edgeTarget.get(i) == 1) {
        GraphNode node = info.get(i + 1);
        if (!node.getVisited()) {
          return dfs_rec(matrix, info, node, n, print, ops);
        }
      }
    }
    return ops;
  }
示例#3
0
  /**
   * Iterative DFS algorithm
   *
   * @return List of nodes in order visited
   */
  public ArrayList<String> dfs_iter(boolean print) {
    ArrayList<String> ops = new ArrayList<>();
    GraphNode v = source;
    List<GraphNode> stack = new ArrayList<>();
    stack.add(v);
    while (stack.size() != 0) {
      v = stack.remove(stack.size() - 1);
      if (v.getVisited() == false) {
        if (print) System.out.println(v);
        ops.add(v.toString());
        v.setVisited(true);

        List<Integer> edgeTarget = matrix.get(v.getID());

        for (int i = 0; i < edgeTarget.size(); ++i) {
          if (edgeTarget.get(i) == 1) {
            GraphNode w = info.get(i + 1);
            stack.add(w);
          }
        }
      }
    }
    return ops;
  }
示例#4
0
 public void resetNodes() {
   for (GraphNode node : info.values()) {
     node.setVisited(false);
   }
 }