Graph building and algorithms