0

I have a class that is used to represent a Person object. Within each Person object there are multiple array lists containing, say, friends, family and other Person objects. I'm now trying to figure out what the best way would be to find the total relatives of that person.

For example:

A has B as family... B has X and Y as family... X has Z as family... and so on.

In the above example, A would have 4 family members up until the person Z. Using nested loops seem like a very bad idea here especially if the data is very large. Suggestion of better data structures or efficient ways to tackle this would be great.

2 Answers2

1

Seems like you're pretty much trying to do a graph traversal. Look at depth first search or breadth first search algorithms and see if you can convert those algorithms to suit your needs

Jamil Seaidoun
  • 949
  • 1
  • 11
  • 24
0

I would suggest use this http://algs4.cs.princeton.edu/41graph/Graph.java.html class and implement DFS or BFS depending on your data. Probably BFS is more efficient for this case, thake a look to this

When is it practical to use DFS vs BFS?

Community
  • 1
  • 1
hlagos
  • 7,690
  • 3
  • 23
  • 41