C++20 sections · 1024 units
Open in Course

Beautiful Matrix - The Idea

Counting steps in grid

The insight: you don't need to simulate the swaps. If the 11 is at position (r,c)(r, c) and needs to reach (3,3)(3, 3), the number of moves is the Manhattan distance: r3+c3|r - 3| + |c - 3|.

Each step moves you one position closer in either rows or columns. Manhattan distance counts how many horizontal and vertical steps you need.

First, find where the 11 is located by scanning the matrix with nested loops.