๐Ÿ“˜ Day 16 โ€“ Teacher's Day Challenge | Beautiful Matrix

TanishiTanishi
2 min read

๐Ÿ—“๏ธ Date: August 09, 2025
๐Ÿงฉ Platform: Codeforces
๐Ÿ”ข Problems Solved Today: 1
๐ŸŽฏ Focus Topic: 2D Arrays, Manhattan Distance


๐Ÿ”— Table of Contents


๐Ÿงฉ Problem 1 โ€“ Beautiful Matrix

๐Ÿ“š Difficulty: Easy-Medium
๐Ÿง  Concepts: 2D Arrays, Absolute Difference, Manhattan Distance


๐Ÿ“„ Problem Statement (Summary):
You are given a 5ร—5 matrix with exactly one cell containing 1 and all other cells containing 0. You can swap adjacent rows or adjacent columns in one move.
The goal is to move the 1 to the center cell (3, 3) (1-indexed). Find the minimum number of moves needed.


๐Ÿ”ข Input Format:
Five lines, each containing five integers (0 or 1). Exactly one integer is 1.

๐Ÿงพ Output Format:
A single integer โ€” the minimum moves to place 1 in the center.

๐Ÿ” Example 1:
Input:

0 0 0 0 0  
0 0 0 0 1  
0 0 0 0 0  
0 0 0 0 0  
0 0 0 0 0

Output:

3

๐Ÿ” Example 2:
Input:

0 0 0 0 0  
0 0 0 0 0  
0 1 0 0 0  
0 0 0 0 0  
0 0 0 0 0

Output:

1

๐Ÿ’ก Approach:

  • Identify the position (row, col) of the 1 in the matrix.

  • The target position is (2, 2) in 0-indexed terms (center).

  • Minimum moves = |row - 2| + |col - 2| (Manhattan Distance).

  • Print the result.


๐Ÿงช Code (C++):

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int mat[5][5];
    int row = -1, col = -1;

    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            cin >> mat[i][j];
            if (mat[i][j] == 1) {
                row = i;
                col = j;
            }
        }
    }

    int count = abs(row - 2) + abs(col - 2);
    cout << count << endl;

    return 0;
}

๐Ÿ“ธ Submission Screenshot:


โœ… Key Takeaways:

  • 2D array scanning is straightforward with nested loops.

  • Manhattan distance formula is perfect for grid movement problems.

  • Breaking down positions into row & column differences simplifies logic.


๐Ÿ“ˆ Daily Summary

MetricValue
Problems Solved1
Topics Covered2D Arrays, Manhattan Distance
Tools UsedC++
Next FocusContinue with Matrix & Grid Problems
Day16 / 43

๐Ÿท๏ธ Tags:
#codeforces #arrays #cpp #beginner #dsa #43DaysChallenge

0
Subscribe to my newsletter

Read articles from Tanishi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tanishi
Tanishi