Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

CAT and MBA Entrance Preparation  Module 3 – Data Interpretation and Logical Reasoning (DILR)

Routes, networks and flows

Find the shortest route in a small network by settling the nearest place first, count grid routes past a closed corner, and balance the flows at junctions.

  • Intermediate
  • 25 minutes
  • Examples run with Python 3.14.8 and Pyodide 314.0.7
  • By MySmartCoPilot
Free core, Pro depth: 10 of 25 minutes free
Free: The shortest route: settle the nearest town first · Grid routes: choose when to turn · Flows: what enters a junction leaves it · Practise: eleven questions on routes, walks and flows. With a pass: 2 in-depth parts and 3 interview answers, about 15 minutes.

What you will learn

  • Find shortest and cheapest routes in a small network
  • Count routes through a grid or a network with stated restrictions
  • Balance the flows at junctions to fill a network's missing values

Before you start

Six towns joined by nine roads hide a 14 km route from A to F that is hard to see by eye, a grid of streets 4 blocks by 3 holds 35 shortest walks, and three unknown flows at four junctions follow one from another.

Routes, networks and flows sets ask for exactly these: the shortest or cheapest route, the number of routes, and the missing flows. Each has a method that needs no guessing: settle the nearest place first, count routes by choosing when to turn, and balance every junction. A program checks every answer by trying every case.

The shortest route: settle the nearest town first

Six towns, A to F, are joined by nine roads, in kilometres: A–B 7, A–C 3, B–C 2, B–D 4, C–D 8, C–E 6, D–E 1, D–F 5 and E–F 7. What is the shortest route from A to F?

Small networks like this one already defeat the eye: the direct road A–B, 7 km, is longer than A–C–B, 5 km. Dijkstra's method: A way to find the shortest distances from one place: again and again, make final the unreached place with the smallest distance found so far and update its neighbours. It needs links of no negative length. gives A distance 0 and leaves every other town unreached. Then, again and again, it takes the unreached town with the smallest distance found so far, makes that distance final, and updates each neighbour whose distance the new town shortens. It needs roads of no negative length, and then no later route can beat a distance made final. Run on tolls instead of kilometres, the same steps find the cheapest route. Step through it, watching the table of distances:

Interactive · step through it Shortest distances from A across the six towns Settle the closest unsettled node, then relax its edges; the table keeps every distance.
Graph of 6 nodes and 9 edges. queue (by dist): A 0.732486157A0B∞C∞D∞E∞F∞queue (by dist):A 0
  • being compared or looked at
  • being moved or written
  • in its final place
  • the key, pivot or target
  • visited or ruled out

Pseudo-code

  1. dist(start) ← 0; dist(v) ← ∞ for every other v; add start to the queue
  2. while the queue is not empty:
  3. u ← the queued node with the smallest dist; settle u
  4. for each edge u → v with weight w:
  5. if dist(u) + w < dist(v): dist(v) ← dist(u) + w; prev(v) ← u; queue v
Distances found so far
Nodedistprev
A0—
B∞—
C∞—
D∞—
E∞—
F∞—

Shortest distances from A. Every node starts at ∞ except A at 0. Each round settles the queued node with the smallest distance: with no negative weights, no later path can beat it.

When it finishes: A: 0, B: 5, C: 3, D: 9, E: 9, F: 14.

Settled 0
Relaxations 0

The towns become final in the order A 0, C 3, B 5, D 9, E 9 and F 14, so the shortest route is A–C–B–D–F, 14 km. The program checks it against every route that visits no town twice, and finds that with road B–D closed the best is A–C–E–D–F, 15 km:

Shortest routes, grid routes and flows, each checked Python · routes/routes.py
"""Shortest routes, grid routes and flows, each checked two ways.

Part 1 runs Dijkstra's method on the lesson's six towns, settling the nearest
unsettled town each time, and checks the answer against every route that visits
no town twice. Part 2 counts the routes across a 4 by 3 grid that move only
right or up, by listing every move sequence and by adding counts point by point.
Part 3 fills the missing flows of the lesson's road network junction by junction.
"""
from itertools import permutations
from math import comb

ROADS = {("A", "B"): 7, ("A", "C"): 3, ("B", "C"): 2, ("B", "D"): 4, ("C", "D"): 8,
         ("C", "E"): 6, ("D", "E"): 1, ("D", "F"): 5, ("E", "F"): 7}
TOWNS = sorted({t for road in ROADS for t in road})


def length(a, b):
    return ROADS.get((a, b)) or ROADS.get((b, a))


dist, came_from, settled = {t: None for t in TOWNS}, {}, []
dist["A"] = 0
while len(settled) < len(TOWNS):
    town = min((t for t in TOWNS if t not in settled and dist[t] is not None), key=lambda t: (dist[t], t))
    settled.append(town)
    for other in TOWNS:
        road = length(town, other)
        if road and other not in settled and (dist[other] is None or dist[town] + road < dist[other]):
            dist[other], came_from[other] = dist[town] + road, town
print("Settled in order:", ", ".join(f"{t} {dist[t]}" for t in settled))
route, t = ["F"], "F"
while t != "A":
    t = came_from[t]
    route.append(t)
print("Shortest A to F:", "-".join(reversed(route)), dist["F"], "km")

def every_route(closed=()):
    """Every route from A to F that visits no town twice, with its length."""
    for k in range(0, 5):
        for middle in permutations([t for t in TOWNS if t not in "AF"], k):
            path = ("A", *middle, "F")
            legs = list(zip(path, path[1:]))
            if all(length(a, b) and {a, b} not in [set(r) for r in closed] for a, b in legs):
                yield sum(length(a, b) for a, b in legs), path


km, path = min(every_route())
print("Every route checked: shortest", km, "km by", "-".join(path))
km, path = min(every_route(closed=[("B", "D")]))
print("With road B-D closed:", "-".join(path), km, "km")

print()
moves = {"".join(p) for p in permutations("RRRRUUU")}
print("Grid, 4 right and 3 up:", len(moves), "routes; C(7, 3) =", comb(7, 3))


def walk(seq):
    x = y = 0
    yield (x, y)
    for m in seq:
        x, y = (x + 1, y) if m == "R" else (x, y + 1)
        yield (x, y)


through = sum((2, 1) in set(walk(m)) for m in moves)
print("Through the blocked point (2, 1):", through, "=", comb(3, 1), "x", comb(4, 2), "| avoiding it:", len(moves) - through)
count = {}
for y in range(4):
    for x in range(5):
        if (x, y) == (2, 1):
            count[(x, y)] = 0
        elif x == 0 and y == 0:
            count[(x, y)] = 1
        else:
            count[(x, y)] = count.get((x - 1, y), 0) + count.get((x, y - 1), 0)
for y in range(3, -1, -1):
    print("   " + " ".join(f"{count[(x, y)]:>3}" for x in range(5)))

print()
a = 500 - 200                     # junction P: 500 in = a + 200 out
b = a + 150 - 100                 # junction Q: a + 150 in = b + 100 out
c = 200 + 100 - 120               # junction R: 200 + 100 in = c + 120 out
print(f"Flows: a = {a}, b = {b}, c = {c}; junction S takes in {b + c} and sends out 530;"
      f" the network takes in {500 + 150} and sends out {120 + 530}")

Output

Settled in order: A 0, C 3, B 5, D 9, E 9, F 14
Shortest A to F: A-C-B-D-F 14 km
Every route checked: shortest 14 km by A-C-B-D-F
With road B-D closed: A-C-E-D-F 15 km

Grid, 4 right and 3 up: 35 routes; C(7, 3) = 35
Through the blocked point (2, 1): 18 = 3 x 6 | avoiding it: 17
     1   4   7  11  17
     1   3   3   4   6
     1   2   0   1   2
     1   1   1   1   1

Flows: a = 300, b = 350, c = 180; junction S takes in 530 and sends out 530; the network takes in 650 and sends out 650

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 routes.py

Taking the shortest road out of each town

Always driving down the shortest road from where you are gives A–C–B–D–E–F: 3 + 2 + 4 + 1 + 7 = 17 km. The road D–E is short, but it leads away from F; only the distances from A tell which town to fix next.

Checkpoint

Check: Shortest routes, nearest town first

  1. Question 1 of 2 After A, which town does Dijkstra's method make final first, and at what distance?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: C, at 3 km

    From A the roads reach B at 7 and C at 3. The method makes final the unreached town with the smallest distance, C at 3, and only then updates B to 3 + 2 = 5.

  2. Question 2 of 2 If road B–C is closed, what is the shortest distance from A to F?

    Type a number.

    A hint

    B is now reached only by the direct road; find the best way to D.

    Show the answer: Question 2 of 2

    Answer: 15 km

    Without B–C, B is 7 km away and D is 11 through B but 10 through C and E (3 + 6 + 1). F is then 10 + 5 = 15 km by A–C–E–D–F, against 16 through E directly.

Grid routes: choose when to turn

A walker crosses a grid of streets 4 blocks east and 3 blocks north, always moving east or north. Every shortest walk has 7 moves, 4 east and 3 north, so a walk is fixed by choosing which 3 of the 7 moves go north: C(7, 3) = 35 routes.

If the corner 2 blocks east and 1 north is closed, subtract the walks through it: 3 ways to reach it, C(3, 1), times 6 ways to go on from it, C(4, 2), which is 18, so 17 walks avoid it. Adding gives the same: each corner’s count is the count of the corner to its west plus the corner to its south, with the closed corner set to 0. The program prints this table:

Walks to each corner 0 east 1 east 2 east 3 east 4 east
3 north 1 4 7 11 17
2 north 1 3 3 4 6
1 north 1 2 closed 1 2
0 north 1 1 1 1 1

Checkpoint

Check: Grid routes by choosing when to turn

  1. Question 1 of 2 How many walks cross a grid 5 blocks east and 2 blocks north, moving only east or north?

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 21 walks

    Each walk has 7 moves, 2 of them north, and choosing those 2 fixes the walk: C(7, 2) = 21.

  2. Question 2 of 2 In the lesson's grid of 4 blocks east and 3 north, how many walks pass the corner 3 east and 1 north?

    Type a number.

    A hint

    Count the walks to the corner and the walks from it to the end, then multiply.

    Show the answer: Question 2 of 2

    Answer: 12 walks

    Reaching the corner takes 3 east and 1 north, C(4, 1) = 4 ways; going on takes 1 east and 2 north, C(3, 1) = 3 ways. Every pair of halves is one walk, so 4 × 3 = 12.

Flows: what enters a junction leaves it

Flows of traffic, water or money obey one rule at every junction: what comes in goes out, which the NIST dictionary calls flow conservation: The rule that at every junction of a network, apart from the points where flow enters or leaves it, what comes in equals what goes out, so each junction gives one equation.. So each junction gives one equation. On a network of one-way roads, 500 vehicles an hour enter at P and 150 at Q, while 120 leave at R and 530 at S. Roads run P to Q (a), P to R (200), Q to R (100), Q to S (b) and R to S (c), so three flows are missing. Start at a junction with only one unknown and work outwards:

Interactive · step by step Four junctions, three missing flows Step through the junctions, starting where only one flow is missing. Each step balances one junction.
Four junctions, three missing flows, step 5 of 5. Showing Junction P (500 in = 300 + 200 out), Junction Q (450 in = 350 + 100 out), Junction R (300 in = 180 + 120 out), Junction S (530 in = 530 out). In focus: Junction S, qs, rs.a200100bcJunction P500 in = 300 + 200 outJunction Q450 in = 350 + 100 outJunction R300 in = 180 + 120 outJunction S530 in = 530 out

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. The network. Vehicles an hour on one-way roads. 500 enter at P and 150 at Q; 120 leave at R and 530 at S. The flows on P to Q, Q to S and R to S, called a, b and c, are missing.
  2. Junction P. Start where only one flow is missing. At P, 500 come in and a + 200 go out, so a = 300.
  3. Junction Q. Q now has one unknown. a + 150 = 450 come in, and b + 100 go out, so b = 350.
  4. Junction R. At R, 200 + 100 = 300 come in, and c + 120 go out, so c = 180.
  5. The check. S has nothing missing, so it checks the work. b + c = 350 + 180 = 530 come in and 530 leave. The whole network balances too, 650 in and 650 out.

P gives a = 300, then Q gives b = 350 and R gives c = 180. Junction S has nothing missing, so it checks the work: 530 in, 530 out, as the program’s last line shows.

Key idea

Balance one junction at a time, starting where only one flow is missing, and let a junction with nothing missing check the work.

Checkpoint

Check: Balancing flows at junctions

  1. Question 1 of 2 At a junction, 240 vehicles an hour arrive on two roads, and 90 leave on one of its two outgoing roads. How many leave on the other?

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 150 vehicles an hour

    What comes in goes out: 240 = 90 + x, so x = 150.

  2. Question 2 of 2 In the lesson's network, why does junction S not need solving once a, b and c are known?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: All its flows are then known, so it can only confirm the work: 350 + 180 in against 530 out

    Four junctions give four equations, but only three flows are missing, and the whole network's in and out must match anyway. So the last junction is a check: if it fails, a flow above it is wrong.

Practise: eleven questions on routes, walks and flows

Eleven untimed questions on the lesson’s network, grid and junctions and on new ones, weakest idea first; a question you miss comes back later.

Practice that adapts to you

Practise this lesson

11 questions about 5 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 11 What does Dijkstra's method do at each step?

    Choose one answer.

    Show the answer: Question 1 of 11

    Answer: It makes final the unreached town with the smallest distance found so far, then updates that town's neighbours

    Each step makes one more town final: the nearest one not yet final. With no negative roads, nothing found later can beat that distance, which is why the order A, C, B, D, E, F gives the right answers.

  2. Question 2 of 11 What is the shortest distance from A to E?

    Type a number.

    Show the answer: Question 2 of 11

    Answer: 9 km

    A–C–E is 3 + 6 = 9 km, and A–C–B–D–E is 3 + 2 + 4 + 1 = 10, so E is made final at 9.

  3. Question 3 of 11 Why does Dijkstra's method need links of no negative length?

    Choose one answer.

    Show the answer: Question 3 of 11

    Answer: With a negative link, a town already made final could later be reached more cheaply

    A distance is made final because every other route to that town would start from a farther town and so be longer. A negative link could shorten such a route afterwards, so the final distance might be wrong.

  4. Question 4 of 11 What is the shortest distance from B to F?

    Type a number.

    Show the answer: Question 4 of 11

    Answer: 9 km

    B–D–F is 4 + 5 = 9 km. Every route that leaves B through C or A is longer: the best of them, B–C–E–D–F, is 14 km.

  5. Question 5 of 11 Why does every walk across 4 blocks east and 3 north have exactly 7 moves?

    Choose one answer.

    Show the answer: Question 5 of 11

    Answer: Each move covers one block east or north, and no move goes back, so 4 + 3 moves are needed

    Moving only east or north, every walk covers 4 blocks east and 3 north, one per move: 7 moves, and choosing which 3 are north fixes the walk.

  6. Question 6 of 11 How many walks cross a grid 3 blocks east and 3 blocks north, moving only east or north?

    Type a number.

    Show the answer: Question 6 of 11

    Answer: 20 walks

    Six moves, three of them north: C(6, 3) = 20.

  7. Question 7 of 11 In the lesson's grid of 4 blocks east and 3 north, how many walks pass the corner (2, 2)?

    Type a number.

    Show the answer: Question 7 of 11

    Answer: 18 walks

    To the corner: 2 east and 2 north, C(4, 2) = 6 ways. From it: 2 east and 1 north, C(3, 1) = 3 ways. So 6 × 3 = 18 walks pass it.

  8. Question 8 of 11 What does flow conservation say about a junction?

    Choose one answer.

    Show the answer: Question 8 of 11

    Answer: What comes into it equals what goes out of it

    At every junction, except where flow enters or leaves the network, in equals out. Each junction therefore gives one equation for its unknown flows.

  9. Question 9 of 11 800 vehicles an hour enter junction X. 350 go from X to Y and the rest from X to Z. Z also receives 120 from Y and sends everything on to W. How many go from Z to W?

    Type a number.

    Show the answer: Question 9 of 11

    Answer: 570 vehicles an hour

    X sends 800 − 350 = 450 to Z. Z takes in 450 + 120 = 570 and sends all of it to W.

  10. Question 10 of 11 Which junction should you balance first?

    Choose one answer.

    Show the answer: Question 10 of 11

    Answer: One with only one unknown flow

    A junction with one unknown flow gives it directly. In the lesson, P had only a missing, then Q only b and R only c, so the flows followed one from another.

  11. Question 11 of 11 Suppose the flow on P to R, 200, were also unknown. What happens to the lesson's network?

    Choose one answer.

    Show the answer: Question 11 of 11

    Answer: One flow stays open: four unknowns face only three independent junction equations

    With four unknowns, P, Q and R each give one equation and S repeats what the others say, so one flow stays open, and the set needs one more fact to fix the flows.

Permutation & Combination Calculator Check a grid count: C(7, 3) = 35 walks across 4 blocks east and 3 north.

Five network and flow sets, fully worked Pro: opens with a Pro, Premium or Ultimate pass

Five sets that add tolls, one-way streets, a corner that must be passed, a road limit and a capacity to the three methods. A program tries every route, walk or flow of each set, so each answer can be checked.

In this part:

  • Tolls: when the cheapest route is not the shortest, with worked numbers
  • One-way streets: count by adding in order
  • A grid with a corner to pass and one to avoid
  • A loop of roads, and a range for one flow
  • The most a network can carry

1 runnable example (Python) · about 5 minutes

Opening this part with your pass…

This part opens with any MySmartCoPilot pass.

  • Pro pass · 1 week₹79$2.99
  • 30 days₹179$5.99
  • 1 year₹1,699$45

One payment; a pass never renews. The price shown is the total you pay: no fees or charges are added at checkout.

It also opens every other in-depth part in Learn and every Pro tool. Sales are final, except where the law gives you a right to withdraw, for example in the EU and the UK (refund policy).

Restrictions that change the count: blocked points, one-way roads and must-pass places Pro: opens with a Pro, Premium or Ultimate pass

Four restrictions on the lesson’s grid and a count by turns, each worked by a rule and checked against all 35 walks, then the same idea for a shortest route that must pass a given town.

In this part:

  • Five rules, each checked against every walk
  • One-way streets in a grid, and turns
  • A town the shortest route must pass
  • Three slips that change the count

1 runnable example (Python) · about 4 minutes

Opening this part with your pass…

This part opens with any MySmartCoPilot pass.

  • Pro pass · 1 week₹79$2.99
  • 30 days₹179$5.99
  • 1 year₹1,699$45

One payment; a pass never renews. The price shown is the total you pay: no fees or charges are added at checkout.

It also opens every other in-depth part in Learn and every Pro tool. Sales are final, except where the law gives you a right to withdraw, for example in the EU and the UK (refund policy).

Interview questions

Warm-up: how many routes cross a grid of m blocks east and n blocks north, moving only east or north?

C(m + n, n). Every such route has m + n moves, m of them east and n north, and it is fixed by choosing which n of the moves go north. A grid 4 blocks by 3 has C(7, 3) = 35 routes. A closed corner removes the routes through it, which are the routes to the corner times the routes from it to the end.

  1. Fresher to mid

    In a network of six towns, a candidate builds a route by always taking the shortest road out of the town they are in, and gets 17 km where the true shortest route is 14 km. Explain why the habit fails, and give a method that cannot fail on such a network.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Fresher to mid

    A walker crosses a grid of streets 6 blocks east and 4 north, moving only east or north, and the corner 3 east and 2 north is closed. How many walks are possible? Show two ways to count, and say which you would trust in a test.

    Model answer, Pro. First step and follow-ups

  3. Fresher to mid

    A network's junction equations leave one flow open. How do you answer "what is the largest flow road X can carry?" and "must road Y carry at least 40?", when no flow can be negative and each road carries at most 60?

    Model answer, Pro. First step and follow-ups

Flashcards · 5 cards

Recall it, then check

Say the answer to yourself before you look: recalling it is what makes it stick.

  1. How does Dijkstra's method find the shortest route?

    Give the start 0, then keep making final the unreached place with the smallest distance found so far, updating its neighbours. With roads of no negative length, no later route can beat a final distance.

  2. Why does taking the shortest road out of each town fail?

    A short road can lead away from the goal: the greedy route through the six towns was 17 km, while settling the nearest town first gave A–C–B–D–F, 14 km.

  3. How many shortest walks cross a grid of 4 blocks east and 3 north?

    Every walk has 7 moves and is fixed by choosing which 3 go north: C(7, 3) = 35. In general C(m + n, n) for m blocks east and n north.

  4. How do you count grid walks that avoid a closed corner?

    Subtract the walks through it: ways to reach it times ways on from it. With the corner 2 east and 1 north closed, 3 × 6 = 18 pass through it, so 35 − 18 = 17 avoid it.

  5. How do you find missing flows in a network?

    What enters a junction leaves it, so each junction gives one equation. Start where only one flow is missing and work outwards; a junction with nothing missing checks the work.

Key takeaways

  • Settle the nearest unreached town first: the six towns gave A–C–B–D–F, 14 km, and the shortest road out of each town gave 17.
  • A grid walk is a choice of when to go north: C(7, 3) = 35 walks, 17 of them avoiding a closed corner.
  • Every junction balances, so start where one flow is missing; a junction with nothing missing checks the work.

Terms in this lesson

Dijkstra's method
A way to find the shortest distances from one place: again and again, make final the unreached place with the smallest distance found so far and update its neighbours. It needs links of no negative length.
flow conservation
The rule that at every junction of a network, apart from the points where flow enters or leaves it, what comes in equals what goes out, so each junction gives one equation.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.