Boundary Traversal of Matrix
Java coding interview problem for Matrix Problems: Boundary Traversal of Matrix.
Boundary traversal is one of the fundamental matrix traversal problems frequently asked in coding interviews.
Unlike:
- Row-wise traversal
- Column-wise traversal
- Spiral traversal
boundary traversal focuses only on the outer edge elements of a matrix.
This problem helps understand:
- Matrix boundaries
- Direction-based traversal
- Index management
- Edge case handling
What is Boundary Traversal of Matrix?
Boundary traversal means visiting only the elements that are present on the outer boundary of a matrix.
For a matrix:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Boundary elements are:
1 2 3 4
5 8
9 12
13 14 15 16
Traversal order:
1 → 2 → 3 → 4 → 8 → 12 → 16 → 15 → 14 → 13 → 9 → 5
Boundary Traversal Direction
The standard clockwise boundary traversal follows:
Top Row
↓
Right Column
↓
Bottom Row
↓
Left Column
Example
Input:
1 2 3
4 5 6
7 8 9
Boundary elements:
Top:
1 2 3
Right:
6 9
Bottom:
8 7
Left:
4
Output:
[1,2,3,6,9,8,7,4]
Understanding Matrix Boundaries
For a matrix:
rows × columns
we have four boundaries:
top
bottom
left
right
Example:
1 2 3 4
5 6 7 8
9 10 11 12
Initial values:
top = 0
bottom = 2
left = 0
right = 3
Boundary Elements Identification
A cell belongs to the boundary if:
row == 0
OR
row == rows-1
OR
column == 0
OR
column == columns-1
Example:
Matrix:
1 2 3
4 5 6
7 8 9
Boundary positions:
(0,0)
(0,1)
(0,2)
(1,0)
(1,2)
(2,0)
(2,1)
(2,2)
Boundary Traversal vs Spiral Traversal
Many developers confuse these two problems.
Boundary Traversal
Only visits:
Outer layer
Example:
1 2 3
4 6
7 8 9
Output:
1 2 3 6 9 8 7 4
Spiral Traversal
Visits:
Complete matrix
Example:
1 2 3
4 5 6
7 8 9
Output:
1 2 3 6 9 8 7 4 5
Difference:
Boundary = Outer elements only
Spiral = All elements layer by layer
Why Is Boundary Traversal Asked in Interviews?
This problem tests:
1. Matrix Index Understanding
Can you correctly handle:
row
column
positions?
2. Boundary Conditions
Can you avoid:
- Duplicate corners
- Missing elements
- Index overflow
3. Algorithm Design
Can you convert:
Visual movement
into
Code logic
?
4. Edge Case Handling
Important cases:
- Single row
- Single column
- One element matrix
- Rectangular matrix
Real-World Applications
Image Processing
Images are represented as:
Pixel Matrix
Boundary pixels are used for:
- Edge detection
- Image cropping
- Border processing
Computer Vision
Object detection algorithms analyze:
- Image borders
- Shape boundaries
Game Development
Grid-based games use boundary traversal for:
- Map borders
- Collision detection
- Board scanning
Robotics
Robot navigation uses boundary movement for:
- Area exploration
- Path planning
Problem Statement
Given a matrix:
m × n
print all boundary elements in clockwise order.
Example 1
Input:
[
[1,2,3],
[4,5,6],
[7,8,9]
]
Output:
[1,2,3,6,9,8,7,4]
Example 2
Input:
[
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
]
Output:
[1,2,3,4,8,12,11,10,9,5]
Constraints
Example:
1 <= rows <= 1000
1 <= columns <= 1000
Approach 1 — Brute Force Boundary Check
The simplest approach:
Traverse the complete matrix.
For every cell, check:
Is it a boundary element?
If yes:
Add it to the result.
Algorithm
For every:
matrix[i][j]
check:
i == 0
OR
i == rows-1
OR
j == 0
OR
j == columns-1
Java Program — Brute Force
import java.util.*;
public class BoundaryTraversalBruteForce {
public static List<Integer> boundaryTraversal(
int[][] matrix) {
List<Integer> result =
new ArrayList<>();
int rows =
matrix.length;
int cols =
matrix[0].length;
for(int i = 0;
i < rows;
i++) {
for(int j = 0;
j < cols;
j++) {
if(i == 0 ||
i == rows - 1 ||
j == 0 ||
j == cols - 1) {
result.add(
matrix[i][j]);
}
}
}
return result;
}
public static void main(String[] args) {
int[][] matrix =
{
{1,2,3},
{4,5,6},
{7,8,9}
};
System.out.println(
boundaryTraversal(matrix));
}
}
Output
[1,2,3,4,6,7,8,9]
Problem With Brute Force Approach
The output order is:
Row traversal order
not:
Clockwise boundary order
Expected:
[1,2,3,6,9,8,7,4]
The algorithm identifies boundary elements but does not maintain traversal direction.
Complexity Analysis
For:
m × n
matrix:
Every element is checked.
Time:
O(m × n)
Space:
O(1)
(excluding output)
Advantages
- Very easy.
- Simple boundary condition.
- Works for all matrices.
Drawbacks
- Wrong traversal order.
- Checks unnecessary inner elements.
- Not preferred in interviews.
Approach 2 — Direction-Based Traversal
Instead of checking every cell:
Directly move through boundaries:
- Top row.
- Right column.
- Bottom row.
- Left column.
Traversal Example
Matrix:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Top row:
1 2 3 4
Right column:
8 12 16
Bottom row:
15 14 13
Left column:
9 5
Approach 2 — Direction-Based Boundary Traversal (Optimal)
The optimal solution directly follows the boundary path instead of checking every matrix element.
The traversal order:
Top Row
↓
Right Column
↓
Bottom Row
↓
Left Column
This avoids unnecessary checks of inner elements.
Algorithm
Given:
rows = matrix.length
columns = matrix[0].length
Initialize:
top = 0
bottom = rows - 1
left = 0
right = columns - 1
Step 1 — Traverse Top Row
Move:
left → right
Add:
matrix[top][column]
Step 2 — Traverse Right Column
Move:
top → bottom
Add:
matrix[row][right]
Step 3 — Traverse Bottom Row
Move:
right → left
Add:
matrix[bottom][column]
Step 4 — Traverse Left Column
Move:
bottom → top
Add:
matrix[row][left]
Important Edge Case Checks
Before traversing:
Bottom Row
Check:
if(top <= bottom)
Otherwise, a single row matrix may be processed twice.
Left Column
Check:
if(left <= right)
Otherwise, a single column matrix may be duplicated.
Java Program — Optimal Boundary Traversal
import java.util.ArrayList;
import java.util.List;
public class BoundaryTraversal {
public static List<Integer> traverse(
int[][] matrix) {
List<Integer> result =
new ArrayList<>();
if(matrix == null ||
matrix.length == 0) {
return result;
}
int rows =
matrix.length;
int cols =
matrix[0].length;
int top = 0;
int bottom = rows - 1;
int left = 0;
int right = cols - 1;
// Top row
for(int col = left;
col <= right;
col++) {
result.add(
matrix[top][col]);
}
top++;
// Right column
for(int row = top;
row <= bottom;
row++) {
result.add(
matrix[row][right]);
}
right--;
// Bottom row
if(top <= bottom) {
for(int col = right;
col >= left;
col--) {
result.add(
matrix[bottom][col]);
}
}
bottom--;
// Left column
if(left <= right) {
for(int row = bottom;
row >= top;
row--) {
result.add(
matrix[row][left]);
}
}
return result;
}
public static void main(String[] args) {
int[][] matrix =
{
{1,2,3},
{4,5,6},
{7,8,9}
};
System.out.println(
traverse(matrix));
}
}
Output
[1, 2, 3, 6, 9, 8, 7, 4]
Step-by-Step Dry Run
Input:
1 2 3
4 5 6
7 8 9
Initial:
top = 0
bottom = 2
left = 0
right = 2
1. Top Row
Traverse:
1 2 3
Result:
[1,2,3]
Update:
top = 1
2. Right Column
Traverse:
6
9
Result:
[1,2,3,6,9]
Update:
right = 1
3. Bottom Row
Traverse:
8 7
Result:
[1,2,3,6,9,8,7]
Update:
bottom = 1
4. Left Column
Traverse:
4
Result:
[1,2,3,6,9,8,7,4]
Final Boundary:
1 2 3 6 9 8 7 4
Complexity Analysis
For:
m × n
matrix:
Every boundary element is visited once.
Time:
O(m + n)
Space:
O(1)
excluding output list.
Advantages
- Optimal traversal.
- No unnecessary matrix scanning.
- Works with rectangular matrices.
- Interview preferred solution.
Drawbacks
- Requires careful boundary checks.
- Corner duplication can happen if conditions are missing.
Clockwise Boundary Traversal
The standard approach:
Top → Right → Bottom → Left
Example:
Input:
1 2 3 4
5 6 7 8
9 10 11 12
Output:
1 2 3 4 8 12 11 10 9 5
Anti-Clockwise Boundary Traversal
Direction:
Top → Left → Bottom → Right
Example:
Input:
1 2 3
4 5 6
7 8 9
Output:
1 4 7 8 9 6 3 2
Java Program — Anti-Clockwise Traversal
import java.util.*;
public class BoundaryAntiClockwise {
public static List<Integer> traverse(
int[][] matrix) {
List<Integer> result =
new ArrayList<>();
int rows =
matrix.length;
int cols =
matrix[0].length;
int top = 0;
int bottom = rows - 1;
int left = 0;
int right = cols - 1;
// Left column
for(int row = top;
row <= bottom;
row++) {
result.add(
matrix[row][left]);
}
left++;
// Bottom row
if(top <= bottom) {
for(int col = left;
col <= right;
col++) {
result.add(
matrix[bottom][col]);
}
bottom--;
}
// Right column
if(left <= right) {
for(int row = bottom;
row >= top;
row--) {
result.add(
matrix[row][right]);
}
right--;
}
// Top row
if(top <= bottom) {
for(int col = right;
col >= left;
col--) {
result.add(
matrix[top][col]);
}
}
return result;
}
}
Rectangular Matrix Handling
Boundary traversal works for:
m × n
matrices.
Example:
3 × 5
Matrix:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
Boundary:
1 2 3 4 5 10 15 14 13 12 11 6
Single Row Matrix
Input:
1 2 3 4
Output:
1 2 3 4
Important:
Do not process bottom row again.
Single Column Matrix
Input:
1
2
3
4
Output:
1 2 3 4
Important:
Do not process left column again.
Recursive Approach
Boundary traversal can be implemented recursively.
Concept:
Process one boundary layer:
Outer boundary
↓
Move inward
↓
Process next layer
However, recursion is not necessary because:
- Only one traversal exists.
- No repeated subproblems.
- Iterative solution is simpler.
Java Streams Approach
Streams are not recommended for boundary traversal.
Reason:
The problem requires:
- Direction control.
- Index movement.
- Boundary updates.
Traditional loops are:
- More readable.
- Faster.
- Easier to debug.
Comparison of Approaches
| Approach | Time Complexity | Space Complexity | Recommendation |
|---|---|---|---|
| Brute Force Check | O(m×n) | O(1) | Learning |
| Direction Traversal | O(m+n) | O(1) | Best Solution |
| Recursive Layer Traversal | O(m×n) | O(min(m,n)) | Alternative |
| Streams | O(m+n) | Extra Objects | Not Preferred |
Matrix Index Mapping
Boundary positions follow:
Top Row
(row = 0)
Columns:
0 → n-1
Right Column
(column = n-1)
Rows:
1 → m-1
Bottom Row
(row = m-1)
Columns:
n-2 → 0
Left Column
(column = 0)
Rows:
m-2 → 1
Primitive vs Object Arrays
Primitive Matrix
int[][]
Advantages:
- Faster.
- Less memory.
- Better cache performance.
Object Matrix
Integer[][]
Advantages:
- Supports null values.
- Works with collections.
Disadvantages:
- More memory.
Common Interview Mistakes
Mistake 1
Printing corners multiple times.
Example:
top row
and
right column
both contain the top-right corner.
Mistake 2
Not checking:
top <= bottom
before bottom traversal.
Mistake 3
Not checking:
left <= right
before left traversal.
Mistake 4
Assuming only square matrices.
Boundary traversal works for:
rectangular matrices
Edge Cases
| Input | Output |
|---|---|
| Empty matrix | [] |
| 1×1 matrix | Single element |
| Single row | All elements |
| Single column | All elements |
| 2×2 matrix | All four elements |
| Rectangular matrix | Works |
Interview Follow-up Questions
Q1. Print boundary elements of matrix.
Q2. Print matrix in spiral order.
Q3. Print anti-clockwise boundary.
Q4. Remove boundary elements.
Q5. Rotate boundary elements.
Q6. Find sum of boundary elements.
Q7. Print matrix layer by layer.
Related Problems
- Spiral Matrix
- Matrix Rotation
- Matrix Transpose
- Diagonal Traversal
- Set Matrix Zeroes
- Search in Matrix
- Matrix Multiplication
Key Takeaways
Boundary traversal is a foundation for advanced matrix algorithms.
The main pattern:
Top Row
↓
Right Column
↓
Bottom Row
↓
Left Column
Optimal solution:
Time: O(m+n)
Space: O(1)
The most important interview concept:
Control boundaries carefully to avoid duplicate corners and missing elements.
Frequently Asked Interview Questions
Q1. What are matrix boundaries?
The first row, last row, first column, and last column.
Q2. Difference between spiral and boundary traversal?
Boundary visits only outer elements.
Spiral visits all elements.
Q3. How do you avoid duplicate corners?
Use correct starting and ending indexes.
Q4. Does it work for rectangular matrices?
Yes.
Interview Tip
When asked:
"Print boundary traversal of matrix."
Explain:
- Maintain four boundaries.
- Traverse four directions.
- Handle single row and column cases.
- Avoid duplicate corner processing.
This demonstrates strong understanding of matrix traversal, boundary control, and algorithm design.