Вот код, который я написал из любопытства по поводу вашей проблемы. Я не знаю много о графиках, но он использует рекурсию, как вы и просили.
В основном вы проходите ввод и для каждого человека вы создаете ArrayList<Integer>
. В этом массиве люди, которые являются непосредственными друзьями этого человека. Например, для 1: {6}, for 2: {7, 6}, for 3: {8, 5}
. Затем, чтобы получить всех друзей человека 2, вы создаете массив compoud ArrayList<Integer>
, собирая массивы для людей 7 и 6 (исключая дубликаты). Таким образом, рекурсия может использоваться таким образом, что функция getAllFriends(Integer person)
должна будет возвращать getAllFriends(Integer person2)
и для ближайших друзей этого человека.
Итак, код может выглядеть примерно так:
public class Test {
public static void main(String[] args) throws Exception {
String input = "1<->6\n" +
"2<->7\n" +
"3<->8\n" +
"4<->9\n" +
"2<->6\n" +
"3<->5";
HashMap<Integer, ArrayList<Integer>> friends = processInput(input); //getting data from the input string and storing it in a structured way
System.out.println(getAllFriends(1, friends, new ArrayList<Integer>(){{add(1);}})); //output: [1, 6, 2, 7]. Double brackets create an anonymous inner class, you add to the result the id of a person whose friends you're collecting
}
public static HashMap<Integer, ArrayList<Integer>> processInput(String input) throws Exception {
HashMap<Integer, ArrayList<Integer>> result = new HashMap<>();
BufferedReader bufReader = new BufferedReader(new StringReader(input));
String line=null;
while( (line=bufReader.readLine()) != null )
{
Integer personLeft = Integer.valueOf(line.substring(0, line.indexOf("<")));
Integer personRight =Integer.valueOf(line.substring(line.indexOf(">")+1, line.length()));
System.out.println(personLeft + ": " + personRight);
if (!result.containsKey(personLeft)) {
result.put(personLeft, new ArrayList<Integer>());
}
result.get(personLeft).add(personRight);
if (!result.containsKey(personRight)) {
result.put(personRight, new ArrayList<Integer>());
}
result.get(personRight).add(personLeft);
}
return result;
}
public static ArrayList<Integer> getAllFriends(Integer person, HashMap<Integer, ArrayList<Integer>> friends, ArrayList<Integer> result) {
for (Integer personFriend: friends.get(person)) {
if (!result.contains(personFriend)) {
result.add(personFriend); //add a person, if it wasn't added before
getAllFriends(personFriend, friends, result); //check out that person's friends
}
}
return result;
}
}