As the question say, how may I create a server- client application using DatagramPacket and DatagramSocket ?
Asked
Active
Viewed 62 times
1
-
1Please [edit] your question the actual output. Also The table is not very clear to me. Why does each node have a root value ? Node 4 is the parent of 6 but 4 is not defined in the table. What does `map` represent ? – c0der Mar 05 '20 at 16:53
-
It looks good, can you please show what exactly the output for your example code is? And have you tried with a simpler graph, like the 12345 example? – kutschkem Mar 06 '20 at 07:55
-
Please add @c0der to your message so I know you replied. Essential information should be in the post and not in comments. – c0der Mar 08 '20 at 04:58
1 Answers
0
See the following solution:
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class DFSTree {
public static ArrayList<Integer> listeIDsOrder = new ArrayList<>();
public static void main (String[] args){
Map<Integer, Integer> map = new HashMap<>();
map.put (1, null); //root
map.put (10, 1);
map.put (11, 10);
map.put (12, 10);
map.put (13, 10);
map.put (20, 1);
map.put (21, 20);
map.put (22, 20);
map.put (30, 1);
map.put (31, 30);
getOrder (1, map);
System.out.println (listeIDsOrder);
}
public static void getOrder (int root, Map<Integer, Integer> graph){
LinkedList<Integer> stack = new LinkedList<>(); //use stack for correct order of processing
stack.add(root); //add root
getOrder(graph, stack);
}
public static void getOrder (Map<Integer, Integer> graph, LinkedList<Integer> stack ){
while(!stack.isEmpty()){
int node = stack.pollFirst(); //for bfs order. for dfs order use stack.pollLast();
listeIDsOrder.add(node);
List<Integer> keys = new ArrayList<>(graph.keySet());
Collections.sort(keys);
for(int key : keys){
if(graph.get(key) != null && graph.get(key) == node) {
stack.add(key);
}
}
}
}
}
Output: [1, 10, 20, 30, 11, 12, 13, 21, 22, 31]

c0der
- 18,467
- 6
- 33
- 65