Arrays & String

Matrix Traversal

A matrix, a fundamental data structure in computer science, is a two-dimensional array of numbers arranged in rows and columns. In this article, we'll delve into the significance of different techniques for traversing a matrix. Matrix traversal, a crucial concept, involves visiting each element of the matrix in a specific order. We'll cover the following traversal techniques:
Row-wise Traversal
Column-wise Traversal
Zigzag Traversal
Spiral Traversal

1. Row-wise Traversal

In row-wise traversal, we visit each element of the matrix row by row, from left to right.

Example

Consider the following 3x3 matrix:
1 2 3
4 5 6
7 8 9
Row-wise Traversal: 1, 2, 3, 4, 5, 6, 7, 8, 9

Pseudocode

for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
System.out.print(matrix[i][j] + " ");
}
}

2. Column-wise Traversal

In column-wise traversal, we visit each element of the matrix column by column, from top to bottom.

Example

Using the same 3x3 matrix:
1 2 3
4 5 6
7 8 9
Column-wise Traversal: 1, 4, 7, 2, 5, 8, 3, 6, 9

Pseudocode

for (int j = 0; j < numCols; j++) {
for (int i = 0; i < numRows; i++) {
System.out.print(matrix[i][j] + " ");
}
}

3. Zigzag Traversal

In zigzag traversal, we traverse the matrix in a zigzag pattern, alternating the direction of traversal for each row.

Example

Using the same 3x3 matrix:
1 2 3
4 5 6
7 8 9
Zigzag Traversal: 1, 2, 3, 6, 5, 4, 7, 8, 9

Pseudocode

for (int i = 0; i < numRows; i++) {
if (i % 2 == 0) {
for (int j = 0; j < numCols; j++) {
System.out.print(matrix[i][j] + " ");
}
} else {
for (int j = numCols - 1; j >= 0; j--) {
System.out.print(matrix[i][j] + " ");
}
}
}

4. Spiral Traversal

In spiral traversal, we traverse the matrix in a spiral pattern, starting from the top-left corner and moving towards the center.

Example

Using the same 3x3 matrix:
1 2 3
4 5 6
7 8 9
Spiral Traversal: 1, 2, 3, 6, 9, 8, 7, 4, 5

Pseudocode

int top = 0, bottom = numRows - 1;
int left = 0, right = numCols - 1;

while (top <= bottom && left <= right) {
// Traverse from left to right
for (int j = left; j <= right; j++) {
System.out.print(matrix[top][j] + " ");
}
top++;

// Traverse from top to bottom
for (int i = top; i <= bottom; i++) {
System.out.print(matrix[i][right] + " ");
}
right--;

// Traverse from right to left
if (top <= bottom) {
for (int j = right; j >= left; j--) {
System.out.print(matrix[bottom][j] + " ");
}
bottom--;
}

// Traverse from bottom to top
if (left <= right) {
for (int i = bottom; i >= top; i--) {
System.out.print(matrix[i][left] + " ");
}
left++;
}
}

Conclusion

That's how you can traverse a matrix using different techniques: row-wise, column-wise, zigzag, and spiral. Each method has its unique way of visiting the elements, which can be useful for different applications.
Happy Coding, and see you next time!
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.