Looks like a "groups'n'islands" scenario with the additional challenge of overlapping groups.
Solutions for this scenario can be found here.
Side note: I'm sorry for being lazy. But without ready to use sample data I just didn't feel to write any code...