Special Matrix

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.

  1. you can swap any two adjacent rows, i and i+1 (0<= i < n-1)

  2. 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 nvector<stringarr)
{
    int rowcolumnmiddle;
    row = column = middle = 0;

    for (int i = 0i < ni++)
    {
        for (int j = 0j < nj++)
        {
            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<stringarr = {{".......",
                           ".*.....",
                           ".......",
                           ".......",
                           ".......",
                           ".......",
                           "......."}};

    cout << specialMatrix(narr<< "\n";

    return 0;
}


No comments:

Post a Comment