Instead of a separate visited array, use the distance array for both purposes:
dist = [infinity] * (n + 1)
dist[s] = 0
queue.push_back(s)
while queue is not empty:
u = queue.pop_front()
for each neighbor v of u:
if dist[v] == infinity:
dist[v] = dist[u] + 1
queue.push_back(v)
Initialize all distances to infinity. Set dist[s] to for the source. When you visit a node , set dist[v] to dist[u] + 1. If a node's distance is still infinity, it has not been visited. This saves memory and makes the code cleaner. After BFS finishes, dist[v] tells you the shortest path length to . If dist[v] is still infinity, is unreachable from the source.