-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq4p1.java
More file actions
90 lines (81 loc) · 2.16 KB
/
Copy pathq4p1.java
File metadata and controls
90 lines (81 loc) · 2.16 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.util.*;
import java.lang.*;
enum State{Unvisited, Visited, Visiting;}
class Node{
State state;
private int value;
public Node(int value){
this.value = value;
}
public int getValue(){
return value;
}
private List<Node> nb = new ArrayList<>();
public void setAdjacent(Node neighbour){
nb.add(neighbour);
}
public List<Node> getAdjacent(){
return nb;
}
}
class Graph{
private int[][] adjacentMatrix;
private List<Node> nodeArr = new ArrayList<>();
public Graph(int n){
adjacentMatrix = new int[n][n];
}
public void initMatrix(int[][] matrix){
}
public List<Node> getNodes(){
return nodeArr;
}
public void initGraph(){
int value = 0;
int len = nodeArr.size();
int cnt = 0;
while(cnt < len){
nodeArr.add(new Node(cnt));
}
while(value < len){
// add some code to init each node's neighbour address
// just put it in Node's field nb.
}
}
}
/* above part is the basic idea to inital graph */
public class q4p1 {
public static void main(String[] args){
//
}
// T: O(n)
// S: O(n)
// A: the hardest part is imagine what method the Graph/ Node class should
// have. The method should be reasonable.
// Ask interviewer!
//
public static boolean search(Graph g, Node start, Node end){
if(start == end) return true;
LinkedList<Node> queue = new LinkedList<>();
for(Node n : g.getNodes()){
n.state = State.Unvisited;
}
start.state = State.Visiting;
queue.add(start);
Node temp;
while(queue.size()>0){
temp = queue.removeFirst();
if(temp != null){
for(Node n : temp.getAdjacent()){
if(n == end)
return true;
if(n.state == State.Unvisited){
n.state = State.Visiting;
queue.add(n);
}
}
}
temp.state = State.Visited;
}
return false;
}
}