Beautiful Matrix

Beautiful Matrix
Codeforces easy

Given a \(5 \times 5\) matrix consisting of \(24\) zeroes and a single \(1\), your task is to find the minimum number of moves required to place the \(1\) in the center of the matrix.

The allowed moves are to swap two vertically or horizonatlly adjacent cells.

Solution

The vertical and horizontal movements are independent, so we can think about them one at a time. If we number the rows from \(1\) to \(5\), the middle row is \(3\). Suppose the \(1\) is currently on row \(r\). Each vertical move shifts it up or down by one row, so it will take \(|r − 3|\) moves to reach the middle row.

In the same way, if we number the columns from \(1\) to \(5\), the middle column is \(3\). If the \(1\) is on column \(c\), it will take \(|c − 3|\) moves to reach the middle column.

Adding these two values gives the total number of moves required: \(|r - 3| + |c - 3|\)

#include<iostream>
using namespace std;

int abs_val(int v) {
    return (v > 0 ? v : -v); // ternary operator which ensures return is positive
}

int main () {
    int r, c;

    for (int i = 1 ; i <= 5 ; i++) {
        for (int j = 1 ; j <= 5 ; j++) {
            int x;
            cin >> x;

            if (x == 1) {
                r = i;
                c = j;
            }
        }
    }

    cout << abs_val(r - 3) + abs_val(c - 3);
}