# Six Degrees

## Question ([LI.531](http://www.lintcode.com/en/problem/six-degrees/))

> Six degrees of separation is the theory that everyone is six or fewer connections away. Given a friendship network, find the degrees of two people, return -1 if one of them cannot be connected.

## Example

```
I: a = 1, b = 4

1------2-----4
 \          /
  \        /
   \--3--/

O: 2

I: a = 1, b= 4

1      2-----4
             /
           /
          3

O: -1
```

## Approach

Level order traversal. Prune the entire search if the level is greater than 6.

## Code

```java
public int sixDegrees(List<UndirectedGraphNode> graph,
                      UndirectedGraphNode person1,
                      UndirectedGraphNode person2) {
    if (person1 == person2) return 0;
    // init queue and set
    Queue<UndirectedGraphNode> queue = new LinkedList<>();
    Set<UndirectedGraphNode> visited = new HashSet<>();
    queue.offer(person1);
    visited.add(person1);
    // bfs by level
    int level = 0;
    UndirectedGraphNode current;
    while (!queue.isEmpty()) {
        int levelSize = queue.size();
        // note: i < queue.size() won't work because we offer and poll elements within that level
        for (int i = 0; i < levelSize; i++) { 
            current = queue.poll();
            if (current == person2) {
                return level;
            }
            for (UndirectedGraphNode friend : current.neighbors) {
                if (!visited.contains(friend)) {
                    queue.offer(friend);
                    visited.add(friend);
                }
            }                
        }
        level++;
        if (level > 6) break;
    }
    return -1;
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://zedive.gitbook.io/project-l/part-2/graph-search/graph-theory/graphthoery_md/six-degrees.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
