Boundary elements of a Matrix
Given a matrix mat[][] of size n*m, the task is to traverse the boundary elements in clockwise order, starting from the top-left element.
Examples:
Input: mat[][] = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12] ]
Output : 1 2 3 4 8 12 11 10 9 5Input: mat[][] = [ [1, 2], [3, 4]]
Output: 1 2 4 3
Approach:
The idea is to traverse the boundary elements of a matrix in clockwise order by breaking down the traversal into four distinct movements: first along the top row from left to right, then down the rightmost column from top to bottom, followed by the bottom row from right to left, and finally up the leftmost column from bottom to top.
Step by step approach:
- Traverse the entire top row from left to right (first row, all columns).
- Traverse the rightmost column from the second row to the last row (all rows except first, last column).
- Traverse the bottom row from second-last column to the first column (last row, all columns except last).
- Traverse the leftmost column from second-last row to the second row (all rows except first and last, first column).
Illustration:
Iteration 1 - Top Row - Left to Right
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]Iteration 2 - Right Column - Top to Bottom
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]Iteration 3 - Bottom Row - Right to Left
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]Iteration 4 - Left Column - Bottom to Top
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
// C++ program to traverse Boundary elements of a Matrix
#include <bits/stdc++.h>
using namespace std;
// Function which traverse Boundary elements of a Matrix
vector<int> boundaryTraversal(vector<vector<int> >& mat) {
int n = mat.size(), m = mat[0].size();
vector<int> res;
// Traverse the top row from left to right
for (int j=0; j<m; j++) {
res.push_back(mat[0][j]);
}
// Traverse the last column, starting from 2nd row
for (int i=1; i<n; i++) {
res.push_back(mat[i][m-1]);
}
// Traverse the bottom row, starting from
// second last column
for (int j=m-2; j>=0; j--) {
res.push_back(mat[n-1][j]);
}
// Traverse the first column from bottom to
// up, starting from second last row and
// ending at second row.
for (int i=n-2; i>0; i--) {
res.push_back(mat[i][0]);
}
return res;
}
int main() {
vector<vector<int>> mat = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
vector<int> res = boundaryTraversal(mat);
for (auto val: res) {
cout << val << " ";
}
cout << endl;
return 0;
}
// Java program to traverse Boundary elements of a Matrix
import java.util.*;
class GfG {
// Function which traverse Boundary elements of a Matrix
static ArrayList<Integer> boundaryTraversal(int[][] mat) {
int n = mat.length, m = mat[0].length;
ArrayList<Integer> res = new ArrayList<>();
// Traverse the top row from left to right
for (int j = 0; j < m; j++) {
res.add(mat[0][j]);
}
// Traverse the last column, starting from 2nd row
for (int i = 1; i < n; i++) {
res.add(mat[i][m - 1]);
}
// Traverse the bottom row, starting from
// second last column
for (int j = m - 2; j >= 0; j--) {
res.add(mat[n - 1][j]);
}
// Traverse the first column from bottom to
// up, starting from second last row and
// ending at second row.
for (int i = n - 2; i > 0; i--) {
res.add(mat[i][0]);
}
return res;
}
public static void main(String[] args) {
int[][] mat = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
ArrayList<Integer> res = boundaryTraversal(mat);
for (int val : res) {
System.out.print(val + " ");
}
System.out.println();
}
}
# Python program to traverse Boundary elements of a Matrix
# Function which traverse Boundary elements of a Matrix
def boundaryTraversal(mat):
n = len(mat)
m = len(mat[0])
res = []
# Traverse the top row from left to right
for j in range(m):
res.append(mat[0][j])
# Traverse the last column, starting from 2nd row
for i in range(1, n):
res.append(mat[i][m - 1])
# Traverse the bottom row, starting from
# second last column
for j in range(m - 2, -1, -1):
res.append(mat[n - 1][j])
# Traverse the first column from bottom to
# up, starting from second last row and
# ending at second row.
for i in range(n - 2, 0, -1):
res.append(mat[i][0])
return res
if __name__ == "__main__":
mat = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
res = boundaryTraversal(mat)
for val in res:
print(val, end=" ")
print()
// C# program to traverse Boundary elements of a Matrix
using System;
using System.Collections.Generic;
class GfG {
// Function which traverse Boundary elements of a Matrix
static List<int> boundaryTraversal(int[][] mat) {
int n = mat.Length, m = mat[0].Length;
List<int> res = new List<int>();
// Traverse the top row from left to right
for (int j = 0; j < m; j++) {
res.Add(mat[0][j]);
}
// Traverse the last column, starting from 2nd row
for (int i = 1; i < n; i++) {
res.Add(mat[i][m - 1]);
}
// Traverse the bottom row, starting from
// second last column
for (int j = m - 2; j >= 0; j--) {
res.Add(mat[n - 1][j]);
}
// Traverse the first column from bottom to
// up, starting from second last row and
// ending at second row.
for (int i = n - 2; i > 0; i--) {
res.Add(mat[i][0]);
}
return res;
}
static void Main(string[] args) {
int[][] mat = new int[][] {
new int[] {1, 2, 3, 4},
new int[] {5, 6, 7, 8},
new int[] {9, 10, 11, 12}
};
List<int> res = boundaryTraversal(mat);
foreach (int val in res) {
Console.Write(val + " ");
}
Console.WriteLine();
}
}
// JavaScript program to traverse Boundary elements of a Matrix
// Function which traverse Boundary elements of a Matrix
function boundaryTraversal(mat) {
let n = mat.length, m = mat[0].length;
let res = [];
// Traverse the top row from left to right
for (let j = 0; j < m; j++) {
res.push(mat[0][j]);
}
// Traverse the last column, starting from 2nd row
for (let i = 1; i < n; i++) {
res.push(mat[i][m - 1]);
}
// Traverse the bottom row, starting from
// second last column
for (let j = m - 2; j >= 0; j--) {
res.push(mat[n - 1][j]);
}
// Traverse the first column from bottom to
// up, starting from second last row and
// ending at second row.
for (let i = n - 2; i > 0; i--) {
res.push(mat[i][0]);
}
return res;
}
let mat = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
];
let res = boundaryTraversal(mat);
console.log(res.join(" "));
Output
1 2 3 4 8 12 11 10 9 5
Time Complexity: O(2*(m + n)) = O(m + n)
Auxiliary Space: O(m + n)
Interesting Pattern Printing Exercise Problem Based on Boundary Elements
Given a matrix of size n x m. Print the boundary elements of the matrix keeping their original positions in a matrix.
Input: [[1, 2, 3, 4],
[5, 6, 7, 8],
[1, 2, 3, 4],
[5, 6, 7, 8]]Output :
1 2 3 4
5 8
1 4
5 6 7 8Input: [[1, 2, 3],
[5, 6, 7],
[1, 2, 3]]
Output:
1 2 3
5 7
1 2 3
Approach
The idea is simple. Traverse the matrix and check for every element if that element lies on the boundary or not, if yes then print the element else print space character
#include <iostream>
#include <vector>
using namespace std;
void printBoundary(vector<vector<int>>& a, int m, int n) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || j == 0 || i == m - 1 || j == n - 1)
cout << a[i][j] << " ";
else
cout << " "; // Two spaces for inner empty elements
}
cout << "\n";
}
}
// Driver code
int main() {
vector<vector<int>> a = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{1, 2, 3, 4},
{5, 6, 7, 8}
};
printBoundary(a, 4, 4);
return 0;
}
#include <stdio.h>
void printBoundary(int a[4][4], int m, int n) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || j == 0 || i == m - 1 || j == n - 1)
printf("%d ", a[i][j]);
else
printf(" "); // Two spaces for inner empty elements
}
printf("\n");
}
}
// Driver code
int main() {
int a[4][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{1, 2, 3, 4},
{5, 6, 7, 8}
};
printBoundary(a, 4, 4);
return 0;
}
import java.util.*;
public class Main {
public static void printBoundary(int[][] a) {
int m = a.length, n = a[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || j == 0 || i == m - 1 || j == n - 1)
System.out.print(a[i][j] + " ");
else
System.out.print(" "); // Two spaces for inner empty elements
}
System.out.println();
}
}
// Driver code
public static void main(String[] args) {
int[][] a = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{1, 2, 3, 4},
{5, 6, 7, 8}
};
printBoundary(a);
}
}
def print_boundary(a):
m, n = len(a), len(a[0])
for i in range(m):
for j in range(n):
if i == 0 or j == 0 or i == m - 1 or j == n - 1:
print(a[i][j], end=' ')
else:
print(' ', end='') # Two spaces for inner empty elements
print()
# Driver code
if __name__ == '__main__':
a = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[1, 2, 3, 4],
[5, 6, 7, 8]
]
print_boundary(a)
using System;
using System.Collections.Generic;
class Program {
static void PrintBoundary(int[,] a) {
int m = a.GetLength(0), n = a.GetLength(1);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || j == 0 || i == m - 1 || j == n - 1)
Console.Write(a[i, j] + " ");
else
Console.Write(" "); // Two spaces for inner empty elements
}
Console.WriteLine();
}
}
// Driver code
static void Main() {
int[,] a = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{1, 2, 3, 4},
{5, 6, 7, 8}
};
PrintBoundary(a);
}
}
function printBoundary(a) {
let m = a.length, n = a[0].length;
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (i === 0 || j === 0 || i === m - 1 || j === n - 1)
process.stdout.write(a[i][j] + ' ');
else
process.stdout.write(' '); // Two spaces for inner empty elements
}
console.log();
}
}
// Driver code
const a = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[1, 2, 3, 4],
[5, 6, 7, 8]
];
printBoundary(a);