This post is completed by 1 user

  • 1
Add to List
Beginner

434. Print boundary of given matrix/2D array.

Objective: Given a two-dimensional array, write a program to print the boundary of the array.

Example:

int [][] grid = new int[][] {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 8, 7, 6},
{5, 4, 3, 2}
Output: 
1  2   3  4
5         8
9         6
5  4   3  2

Approach: 

Iterate the two-dimensional array and print the array elements on the following conditions-

For element at (h, w)

  • If h is either 0 or height-1, print the element. (this will print the first and last row)
  • Else if either w>0 or width-1, print just a white space. (this will skip all the elements in the middle of the array.
  • Else print the element (this will print first and last element of middle rows) '

Output: 

1  2   3  4
5         8
9         6
5  4   3  2