Boundry Traversal of the Matrix
Question – You are given a matrix of dimensions n x m. The task is to perform boundary traversal on the matrix in a clockwise manner.
Example
Given Input: n = 4, m = 4
matrix[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15,16}}
Expected Output: 1 2 3 4 8 12 16 15 14 13 9 5
Logic
- Traverse the top row
- Traverse the last column
- Traverse the bottom row
- Traverse the bottom row
Code
static ArrayList<Integer> boundaryTraversal(int matrix[][], int n, int m) { // Create a list to store the boundary elements ArrayList<Integer> list = new ArrayList<>(); // Get the number of rows and columns in the matrix int rows = matrix.length; int cols = matrix[0].length; // Traverse the top row from left to right for (int i = 0; i < cols; i++) { list.add(matrix[0][i]); } // Traverse the last column from top to bottom for (int i = 1; i < rows; i++) { list.add(matrix[i][cols - 1]); } // Traverse the bottom row from right to left if (rows > 1) { for (int i = cols - 2; i >= 0; i--) { list.add(matrix[rows - 1][i]); } } // Traverse the first column from bottom to top if (cols > 1) { for (int i = rows - 2; i > 0; i--) { list.add(matrix[i][0]); } } // Return the list containing the boundary elements return list; }