You are given a square matrix of size n (it will be an odd integer). Rows are indexed 0 to n-1 from top to bottom and columns are indexed 0 to n-1 from left to right. The matrix consists of only '*' and '.'. '*' appears only once in the matrix while all other positions are occupied by '.'
Your task is to convert this matrix to a special matrix by following any of two operations any number of times.
you can swap any two adjacent rows, i and i+1 (0<= i < n-1)
you can swap any two adjacent columns, j and j+1 (0<= j < n-1)
Special Matrix is one that contains '*' at the middle of the matrix. e.g following is a size 7 special matrix
.......
.......
.......
...*...
.......
.......
.......
Output no of steps to convert given matrix to special matrix.
Example:
Input: n = 7, arr = {{".......", ".*.....", ".......", ".......", ".......", ".......", "......."}}
Output: 4
Approach
C++
#include <bits/stdc++.h>using namespace std;int specialMatrix(int n, vector<string> arr){int row, column, middle;row = column = middle = 0;for (int i = 0; i < n; i++){for (int j = 0; j < n; j++){if (arr[i][j] == '*'){row = i;column = j;}}}middle = n / 2;row -= middle;column -= middle;if (row < 0){row = -row;}if (column < 0){column = -column;}return row + column;}int main(){int n = 7;vector<string> arr = {{".......",".*.....",".......",".......",".......",".......","......."}};cout << specialMatrix(n, arr) << "\n";return 0;}
No comments:
Post a Comment