35S-Section-Solution - CS106X Autumn 2010 Handout 35S...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
CS106X Handout 35S Autumn 2010 December 1 st – 3 rd , 2010 Section Solution Solution 1: People You May Know We use a brute force double foreach loop to gain access to all of your friends’ friends. We maintain a peopleYouAlreadyKnow set (yourself, all of your friends) so that we don’t accidentally include a friend in the return value. The solution here makes the reasonable assumption that each user is uniquely identified by the address of his or her user record. Set<user *> getFriendsOfFriends(user *loggedinuser) { Set<user *> peopleYouMayKnow; Set<user *> peopleYouAlreadyKnow = loggedinuser->friends; peopleYouAlreadyKnow.add(loggedinuser); foreach (user *fr in loggedinuser->friends) { foreach (user *friendOfFriend in fr->friends) { if (!peopleYouAlreadyKnow.contains(friendOfFriend)) { peopleYouMayKnow.add(friendOfFriend); } } } return peopleYouMayKnow; } Note that there’s no real need to check to see if a friend of a friend has already been added to the peopleYouMayKnow set. There’s no harm in adding the same item multiple times, as the set discard any and all duplicates anyway. Solution 2: Detecting Cycles This is a variation on the depth-first traversal example we went over in lecture. The trick is to maintain a list of nodeT * s actively being explored, and if we ever trip over such a node during our exploration, then we know we have a cycle and need to report that back. The one feature of this particular solution is that it properly handles those graphs that aren’t
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/13/2011 for the course CS 106X taught by Professor Cain,g during the Fall '08 term at Stanford.

Page1 / 4

35S-Section-Solution - CS106X Autumn 2010 Handout 35S...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online