๐ Day 16 โ Teacher's Day Challenge | Beautiful Matrix


๐๏ธ Date: August 09, 2025
๐งฉ Platform: Codeforces
๐ข Problems Solved Today: 1
๐ฏ Focus Topic: 2D Arrays, Manhattan Distance
๐ Table of Contents
Daily Summary
๐งฉ 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 the1
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
Metric | Value |
Problems Solved | 1 |
Topics Covered | 2D Arrays, Manhattan Distance |
Tools Used | C++ |
Next Focus | Continue with Matrix & Grid Problems |
Day | 16 / 43 |
๐ท๏ธ Tags:#codeforces #arrays #cpp #beginner #dsa #43DaysChallenge
Subscribe to my newsletter
Read articles from Tanishi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
