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) ‘

Complete Code:

Output: 

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

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

%d bloggers like this: