← All lints

cycle_by_colors

L0565Idiomswarn

Directed cycle found by colouring a DFS by hand

color[u] = 1; ... if color[v] == 1: cyc = true; ... color[u] = 2: find_cycle(g)

Flagged
let (n, m): (1..=100000, 0..=200000) = read()
var out: List<List<Int>> = [[] for _ in 0..=n]
for _ in 0..m:
    let (u, v): (1..=n, 1..=n) = read()
    out[u].push(v)
var color: List<Int> = [0 for _ in 0..=n]
var cyc = false
fn dfs(u: Int):
    color[u] = 1
    for v in out[u]:
        if color[v] == 1:
            cyc = true
        elif color[v] == 0:
            dfs(v)
    color[u] = 2
for u in 1..=n:
    if color[u] == 0:
        dfs(u)
print(yes(cyc))
Write instead
use std.graph.{find_cycle}
let (n, m): (1..=100000, 0..=200000) = read()
domain V = 1..=n
let edges: [0..m](u: V, v: V) = read()
let g = Graph.directed(edges)
print(yes(find_cycle(g) != None))

Why

Marking a vertex 1 when the DFS enters it and 2 when it leaves, and calling an arc into a vertex still marked 1 a cycle, is the three-colour test for a directed cycle. Written by hand it needs the colour list, a flag set from inside the recursion, and recursion deep enough to overflow on a long path. find_cycle(g) from std.graph runs the same test without recursion and returns the cycle itself (None when there is none), so find_cycle(g) != None asks the question and the cycle is there when the answer needs it. When the real question is an order, topo(g) returns one or None. There is no automatic fix, since the graph has to be typed over a vertex domain first. A two-colouring for bipartiteness (paint(v, 3 - c)) is a different test and is not reported.

The practice it serves

A hand-written pattern the language or the standard library already says in one step.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
let (n, m): (1..=100000, 0..=200000) = read()
var adj: List<List<Int>> = [[] for _ in 0..=n]
for _ in 0..m:
    let (u, v): (1..=n, 1..=n) = read()
    adj[u].push(v)
    adj[v].push(u)
var color: List<Int> = [0 for _ in 0..=n]
var odd = false
fn paint(u: Int, c: Int):
    color[u] = c
    for v in adj[u]:
        if color[v] == c:
            odd = true
        elif color[v] == 0:
            paint(v, 3 - c)
for u in 1..=n:
    if color[u] == 0:
        paint(u, 1)
print(yes(not odd))

Turn it off

For one block, wrap it in with lint(cycle_by_colors: allow):. For a project, add cycle_by_colors = "allow" under [lints] in cp.toml.

Generated from spec/lints/cycle_by_colors, the same record the linter is built from.