← All lints

components_by_dfs

L0560Idiomswarn

Components counted by DFS by hand

for u ..: if not seen[u]: count += 1; visit(u): components(adj)

Flagged
let (n, m): (1..=1000, 0..=1000) = read()
var adj: List<List<Int>> = [[] for _ in 0..n]
for _ in 0..m:
    let (a, b): (0..n, 0..n) = read()
    adj[a].push(b)
    adj[b].push(a)
var seen: List<Bool> = [false for _ in 0..n]
fn visit(u: Int):
    seen[u] = true
    for v in adj[u] if not seen[v]:
        visit(v)
var comps = 0
for u in 0..n:
    if not seen[u]:
        comps += 1
        visit(u)
print(comps)
Write instead
use std.graph.{components}
domain V = 0..4
let g: [V]List<V> = [[2], [], [0], []]
let (domain C, comp) = components(g)
print(C.count)

Why

Starting a search from every vertex not yet seen and counting the starts counts connected components, with a seen list, a recursive visit and the counter written by hand (and recursion deep enough to overflow on a path). components(adj) from std.graph returns the component domain C and comp[v] for every vertex: C.count is how many there are, and comp[u] == comp[v] asks whether two vertices are connected. There is no automatic fix, since the graph has to be typed over a domain first.

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..=1000, 0..=1000) = read()
var adj: List<List<Int>> = [[] for _ in 0..n]
for _ in 0..m:
    let (a, b): (0..n, 0..n) = read()
    adj[a].push(b)
    adj[b].push(a)
var seen: List<Bool> = [false for _ in 0..n]
fn visit(u: Int):
    seen[u] = true
    for v in adj[u] if not seen[v]:
        visit(v)
for u in 0..n:
    if not seen[u]:
        visit(u)
print(yes(seen[0]))

Turn it off

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

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