Last Updated: 20 May, 2022

Matrix Boundary Traversal

Easy
Asked in company
Amazon

Problem statement

Given a matrix of integers containing ‘M’ rows and ‘N’ columns. Print the boundary elements of the matrix. The order of printing does not matter.

Note :

The output you will see will be in sorted order.
Your order of output does not matter.
You can return your result in any order.
Example :
Input: ‘M’ = 2, ‘N’ = 2, ‘MAT’ = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

input

Output: [1, 2, 3, 4, 5, 8, 9, 12, 13, 14, 15, 16]
If we traverse the matrix in clockwise order from the top left then it will be 1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5. Which in output will be shown in sorted order which is 1, 2, 3, 4, 5, 8, 9, 12, 13, 14, 15, 16.

output

Referring to the image above, we are printing only the elements that lie on the boundary.

Input Format :
The first line will contain the integer 'T', denoting the number of test cases.

The first line of each test contains two integers ‘M’ and ‘N’ respectively.

The Next ‘M’ line contains ‘N’ elements denoting the matrix.
Output format :
For each test case print the boundary elements.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
2 <= T <= 10
1 <= N, M <= 2000

Time Limit: 1 sec

Approaches

01 Approach

We can traverse the whole matrix and print only those elements that are boundary elements and for all the other elements we can mark them as whitespace.

 

The steps are as follows:-

  1. Declare another matrix that stores the boundary values named 'ans'.
  2. Traverse the matrix.
  3. For i in the range[0, m-1].
    • For j in range[0, n-1].
      • Check if the i is 0 or m-1 or if j is 0 or j is n-1.
        • Append the value of 'mat[i][j]' into 'ans'.
  4. Return ‘ans’.

02 Approach

We can create a 2D matrix of size M*N initialized with ‘ ‘. We will traverse only the first row and last row and update the values with ‘MAT’ values of the corresponding also we will traverse the first column and last column and update the values of ‘ans’ with ‘MAT’ values.

 

The steps are as follows:-

  1. Declare another matrix that stores the boundary values named as 'ans' default value with ' '.
  2. Fill the first row.
  3. Fill the last row.
  4. Fill in the first column.
  5. Do not insert the first and last elements.
  6. Fill in the last column.
  7. Do not insert the first and last elements.
  8. Return ‘ans’.