在BFS中搜索特定节点的邻居

时间:2018-03-20 08:00:55

标签: java depth-first-search breadth-first-search

我在搜索方法中实现逻辑部分时遇到了问题。

所有值都作为main方法的输入,然后将这些值传递给函数。

我想要的输出:特定节点有多少邻居

下面给出了代码,输入和测试用例的所需输出

输入值

6
India
Pakistan
Nepal
Bhutan
Bangladesh
China
0   1   1   1   1   1
1   0   0   0   0   0
1   0   0   1   0   1
1   0   1   0   0   1
1   0   0   0   0   0
1   0   1   1   0   0
Bhutan

Output Put 
3



class DFSUtil {

  static int search(List<Node<String>> graph, int[][] adjacencyMatrix,
          Node<String> startNode, String searchString) {//START search METHOD
      //Here i want logic 
      // USE findNeighbours METHOD TO FIND NEIGBOURS USING ADJACENCY 
      return 0;

  }//END OF search

  //DO NOT EDIT THE FOLLOWING METHOD
  static List<Node<String>> findNeighbours(int[][] adjacencyMatrix,
          List<Node<String>> graph, Node<String> node) {
      int index = -1;
      ArrayList<Node<String>> neighbours = new ArrayList<>();

      for (int idx = 0; idx < graph.size(); idx++) {
          if (graph.get(idx).equals(node)) {
              index = idx;

              break;
          }
      }

      if (index != -1) {
          for (int idx = 0; idx < adjacencyMatrix[index].length; idx++) {
              if (adjacencyMatrix[index][idx] == 1) {
                  neighbours.add(graph.get(idx));
              }
          }
      }
      return neighbours;
  }
}
//DO NOT  EDIT THE CLASS
class Node<T> {
    private T data;
    private boolean visited;
    private int nodeIndex;

    public Node(T data, int nodeIndex) {
        this.data = data;
        this.nodeIndex = nodeIndex;
    }

    public final int getNodeIndex() {
        return nodeIndex;
    }

    public final boolean isVisited() {
        return visited;
    }

    public final void setVisited(boolean visited) {
        this.visited = visited;
    }

    public final T getData() {
        return data;
    }

    @Override
    public boolean equals(Object obj) {
        if (null == obj) {
            return false;
        }
        if (!(obj instanceof Node)) {
            return false;
        }
        Node<T> otherNode = (Node<T>) obj;
        if (this.getData().equals(otherNode.getData())) {
            return true;
        }
        return false;
    }

}

0 个答案:

没有答案