s LearnSqueak.com

SMALLTALK LAB

Bipartite graphs: color neighbors into opposite teams

Use a breadth-first traversal to split an undirected graph into two sides, find same-color conflicts, and test disconnected components with native Smalltalk checkpoints.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Use native Squeak 6.1 and a Workspace. Select each complete expression and choose Print it. Vertices are integers from 1 through graph size. Each adjacency Array lists neighboring vertex numbers, and every undirected edge appears in both directions. This lesson is about two-color feasibility, not finding shortest paths or an optimal graph coloring.

These are native Squeak 6.1 examples. Each checkpoint is independent: open the download as text, copy one complete expression into Workspace and choose Print it. Do not file in the checkpoint collection as a class definition.

01 - Read an undirected graph

A four-cycle has edges 1-2, 2-3, 3-4 and 4-1. The adjacency list stores each undirected edge twice. Starting with a small explicit fixture makes it possible to inspect every constraint.

Independent Workspace expression - select all, then Print it
| graph |
graph := #(#(2 4) #(1 3) #(2 4) #(1 3)).
{graph size. graph at: 1. graph at: 3}

Expected: #(4 #(2 4) #(2 4))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Read an undirected graph
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Draw four dots in a square and check both directions of each edge. Missing a reverse edge violates this lesson's input contract.

Download this checkpoint

02 - Encode unknown and opposite colors

Use zero for undiscovered vertices, and 1 or -1 for the two sides. Negating a known color produces the required neighbor color. Zero is not a third team; it means no decision has been made.

Independent Workspace expression - select all, then Print it
| colors |
colors := Array new: 4 withAll: 0.
colors at: 1 put: 1.
colors at: 2 put: (colors at: 1) negated.
colors

Expected: #(1 -1 0 0)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Encode unknown and opposite colors
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: A neighbor of vertex 2 must receive 1. Check the color is nonzero before treating negation as a team switch.

Download this checkpoint

03 - Discover the first frontier once

Color neighbors when you enqueue them, not when you eventually remove them. Otherwise two parents can add the same unseen vertex repeatedly. Here processing vertex 1 discovers vertices 2 and 4.

Independent Workspace expression - select all, then Print it
| graph colors queue vertex |
graph := #(#(2 4) #(1 3) #(2 4) #(1 3)).
colors := Array new: 4 withAll: 0. colors at: 1 put: 1.
queue := OrderedCollection with: 1.
vertex := queue removeFirst.
(graph at: vertex) do: [:neighbor |
 (colors at: neighbor) = 0 ifTrue: [
  colors at: neighbor put: (colors at: vertex) negated.
  queue addLast: neighbor]].
{colors. queue asArray}

Expected: #(#(1 -1 0 -1) #(2 4))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Discover the first frontier once
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The queue lists work left to do. The colors include discovered vertices that have not been processed yet.

Download this checkpoint

04 - Check already colored neighbors too

An edge is satisfied only when its endpoints have opposite colors. Reaching an already colored neighbor is normal in an undirected graph; do not report every revisit as a cycle error. Only matching nonzero colors violate the two-team constraint.

Independent Workspace expression - select all, then Print it
| colors edges |
colors := #(1 -1 1 -1).
edges := #(#(1 2) #(2 3) #(3 4) #(4 1) #(1 3)).
edges collect: [:edge |
 (colors at: edge first) ~= (colors at: edge second)]

Expected: #(true true true true false)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Check already colored neighbors too
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The diagonal 1-3 fails: both ends have color 1. Adding it to the square creates an odd cycle.

Download this checkpoint

05 - Traverse every connected component

The outer loop starts a fresh breadth-first search whenever it finds an uncolored root. This includes isolated vertices and disconnected components. The returned Array contains a validity flag and the assigned colors; on failure those colors are only a traversal record, not a valid partition.

Independent Workspace expression - select all, then Print it
| colorGraph |
colorGraph := [:graph | | colors queue valid |
 colors := Array new: graph size withAll: 0. valid := true.
 1 to: graph size do: [:root |
  (colors at: root) = 0 ifTrue: [
   colors at: root put: 1. queue := OrderedCollection with: root.
   [queue isEmpty] whileFalse: [| vertex |
    vertex := queue removeFirst.
    (graph at: vertex) do: [:neighbor |
     (colors at: neighbor) = 0
      ifTrue: [colors at: neighbor put: (colors at: vertex) negated.
       queue addLast: neighbor]
      ifFalse: [(colors at: neighbor) = (colors at: vertex)
       ifTrue: [valid := false]]]]]].
 {valid. colors}].
colorGraph value: #(#(2 4) #(1 3) #(2 4) #(1 3))

Expected: #(true #(1 -1 1 -1))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Traverse every connected component
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: All four square edges join opposite colors. Globally swapping 1 and -1 would also be a valid answer, so this exact pattern is a traversal convention.

Download this checkpoint

06 - Reject a triangle and a self-loop

Three pairwise connected vertices form an odd cycle. After the root assigns both neighbors -1, their mutual edge exposes a conflict. A self-loop also conflicts immediately because its endpoints are the same vertex.

Independent Workspace expression - select all, then Print it
| colorGraph |
colorGraph := [:graph | | colors queue valid |
 colors := Array new: graph size withAll: 0. valid := true.
 1 to: graph size do: [:root |
  (colors at: root) = 0 ifTrue: [
   colors at: root put: 1. queue := OrderedCollection with: root.
   [queue isEmpty] whileFalse: [| vertex |
    vertex := queue removeFirst.
    (graph at: vertex) do: [:neighbor |
     (colors at: neighbor) = 0
      ifTrue: [colors at: neighbor put: (colors at: vertex) negated.
       queue addLast: neighbor]
      ifFalse: [(colors at: neighbor) = (colors at: vertex)
       ifTrue: [valid := false]]]]]].
 {valid. colors}].
{(colorGraph value: #(#(2 3) #(1 3) #(1 2))) first.
 (colorGraph value: #(#(1))) first}

Expected: #(false false)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Reject a triangle and a self-loop
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The algorithm continues after finding a conflict so that the final colors still record a complete traversal. The boolean is authoritative.

Download this checkpoint

07 - Handle disconnected and empty inputs

An isolated vertex can belong to either side. A disconnected graph must have each component checked independently; one good component does not prove that another component is bipartite. The empty graph has no violated edge.

Independent Workspace expression - select all, then Print it
| colorGraph |
colorGraph := [:graph | | colors queue valid |
 colors := Array new: graph size withAll: 0. valid := true.
 1 to: graph size do: [:root |
  (colors at: root) = 0 ifTrue: [
   colors at: root put: 1. queue := OrderedCollection with: root.
   [queue isEmpty] whileFalse: [| vertex |
    vertex := queue removeFirst.
    (graph at: vertex) do: [:neighbor |
     (colors at: neighbor) = 0
      ifTrue: [colors at: neighbor put: (colors at: vertex) negated.
       queue addLast: neighbor]
      ifFalse: [(colors at: neighbor) = (colors at: vertex)
       ifTrue: [valid := false]]]]]].
 {valid. colors}].
{colorGraph value: #(#(2) #(1) #() #(5) #(4)).
 colorGraph value: #().
 (colorGraph value: #(#() #(3 4) #(2 4) #(2 3))) first}

Expected: #(#(true #(1 -1 1 1 -1)) #(true #()) false)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Handle disconnected and empty inputs
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The last fixture begins with an isolated vertex, followed by a triangle. A search from only vertex 1 would incorrectly miss that triangle.

Download this checkpoint

08 - Verify the partition against every edge

Independently check that every vertex has a real color and every listed edge joins opposite colors. This validates a successful output without trusting the traversal's own validity flag. It also explains the certificate: the color Array is easy to check.

Independent Workspace expression - select all, then Print it
| colorGraph fixture result painted edgeCheck |
colorGraph := [:graph | | colors queue valid |
 colors := Array new: graph size withAll: 0. valid := true.
 1 to: graph size do: [:root |
  (colors at: root) = 0 ifTrue: [
   colors at: root put: 1. queue := OrderedCollection with: root.
   [queue isEmpty] whileFalse: [| vertex |
    vertex := queue removeFirst.
    (graph at: vertex) do: [:neighbor |
     (colors at: neighbor) = 0
      ifTrue: [colors at: neighbor put: (colors at: vertex) negated.
       queue addLast: neighbor]
      ifFalse: [(colors at: neighbor) = (colors at: vertex)
       ifTrue: [valid := false]]]]]].
 {valid. colors}].
fixture := #(#(2 4) #(1 3) #(2 4) #(1 3) #()).
result := colorGraph value: fixture. painted := result second.
edgeCheck := (1 to: fixture size) allSatisfy: [:vertex |
 (fixture at: vertex) allSatisfy: [:neighbor |
  (painted at: vertex) = (painted at: neighbor) negated]].
{result first. painted allSatisfy: [:c | c = 1 or: [c = -1]]. edgeCheck}

Expected: #(true true true)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Verify the partition against every edge
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try adding the diagonal in both directions. The color check still confirms assigned colors, but edgeCheck and the traversal validity flag become false.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Bipartite graphs: color neighbors into opposite teams native visual trace
Replay of actual Morphic window captures at successive computed stages; not mouse footage.

Download the visual experiment. Select the entire expression and Do it. Change stage := 0. to another supported stage, close the previous window, and run again. The GIF replays those native states. This example needs native Squeak; no new browser playground compatibility is claimed.

Reason about correctness and limits

The input must be an undirected adjacency Array with integer neighbor indexes inside 1..graph size. No parser or full validation is provided. If your source lists edges only once, first build both adjacency directions; do not silently interpret a directed graph as this input.

A graph is bipartite exactly when it contains no odd cycle. Along an edge the color flips; walking around an odd cycle would demand that a vertex have its own opposite color. The traversal detects a violated edge but does not reconstruct an odd-cycle witness.

For a successful result, each connected component may have its two colors swapped independently. An isolated vertex is assigned 1 by convention. The color Array is not a unique partition and it does not optimize team sizes.

Each vertex is enqueued once and every adjacency entry is inspected once, giving O(V+E) traversal operations with a constant-time FIFO queue. This teaching implementation uses OrderedCollection removeFirst: its concrete storage and removal cost are implementation-dependent. For a strict scalable bound use an indexed FIFO or the ring-buffer approach rather than assuming every collection operation is constant-time.

A failed result still includes assigned colors, but those colors do not satisfy every edge. Check the boolean before presenting the result as a valid partition. Duplicate edges do not change feasibility; self-loops always fail.

Three practice challenges

Add a diagonal

What happens when you add edge 1-3 to the square in both adjacency lists?

Show solution

The graph becomes non-bipartite: 1-2-3-1 is a triangle. The BFS assigns colors 1 and -1 to adjacent layers, then an edge connects equal colors.

Swap a component

For the disconnected graph in step 7, can vertices 4 and 5 use -1 and 1 instead?

Show solution

Yes. Their component has only one edge, so swapping both endpoints preserves the opposite-color condition without affecting vertices 1, 2 or 3.

Build a slower oracle

How could you independently test a tiny graph without BFS?

Show solution

Enumerate all 2^V assignments of two colors and accept if any assignment makes every edge cross colors. This is exponential and unsuitable for large graphs, but it is an excellent exhaustive oracle for small fixtures.

Continue learning

Pathfinding | Stacks Queues | Union Find

Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Linux.