Here is the full solution:
function buildTeams():
read n, m
graph := array of n + 1 empty lists
for i from 1 to m:
read a, b
graph[a].append(b)
graph[b].append(a)
color := array of size n + 1, all 0
for i from 1 to n:
if color[i] = 0 then
if not bfs(i, 1, graph, color) then
print "IMPOSSIBLE"
return
for i from 1 to n:
print color[i]
The BFS function is the same as before: color nodes, check conflicts. On success, output each color plus one.
This runs in time and uses space.