Jishan's Log 8: Codeforces 263A solution
Codeforces 263A: A Beautiful Matrix
What the problem wants?
The problem states that a 5x5 matrix is given. It is full of 0's except one position has the number 1. We need to find the minimum moves needed to shift 1 from its current position to the center of the matrix.
How to solve it?
The Algorithm:
1) take a matrix and its input.
2) search for 1. If found, then find the absolute value from where it is to the center of the matrix. Do this for both i & j position.
***NOTE: The logic here is that the minimum moves made will only be through the horizontal or vertical movement. not cross movements. So we take the i at that position and subtract it to the i of the center element. Same for j.
The Code:
#include<bits/stdc++.h>
using namespace std;
#define fastio ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
void minMoves(int matrix[5][5])
{
int i_idx = 0, j_idx = 0;
for(int i=0; i<5; i++)
{
for(int j=0; j<5; j++)
{
if(matrix[i][j] == 1)
{
i_idx = abs(i-2);
j_idx = abs(j-2);
cout << i_idx + j_idx << "\n";
break;
}
}
}
}
int main()
{
fastio;
int matrix[5][5];
for(int i=0; i<5; i++)
{
for(int j=0; j<5; j++)
{
int x; cin >> x;
matrix[i][j] = x;
}
}
minMoves(matrix);
}
Comments
Post a Comment