Approach
-
It can be done with naive approach which will take O(n^m)
-
iterate through all elements
-
Check if an element is on boundary or not
i ==0|| j ==0|| i == mat.length -1
|| j == mat[i].length - 1
- Optimize it by considering only first and last rows and first and the last columns
- Print the first row of the matrix.
- Print the last column of the matrix except the first row.
- Print the last row of the matrix except the last column.
- Print the first column of the matrix except the first and last row.
Break it down
- four_for_loops
- print_first_row
- print_last_column-first_row
- print_last_row-last_column
- print_first_column-first_row-last_row
Code
# Python program of the above approach
# Function to print the boundary elements
# of the matrix in clockwise
def boundaryTraversal(arr, N, M):
# Print the first row
for i in range(M):
print(arr[0][i], end = " ");
# Print the last column
# except the first row
for i in range(1, N):
print(arr[i][M - 1], end = " ");
# Print the last row
# except the last column
if (N > 1):
# Print the last row
for i in range(M - 2, -1, -1):
print(arr[N - 1][i], end = " ");
# Print the first column except
# the first and last row
if (M > 1):
# Print the first column
for i in range(N - 2, 0, -1):
print(arr[i][0], end = " ");
# Driver Code
if __name__ == '__main__':
arr = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
N = len(arr);
M = len(arr[0]);
# Function Call
boundaryTraversal(arr, N, M);