March 12, 2025

Matrix Traversal

Matrix traversal is a fundamental concept in computer science and is widely used in various applications, from image processing to graph theory. Traversing a matrix efficiently is crucial for solving problems involving grid-based data structures. This article explores different matrix traversal techniques and their applications.

Types of Matrix Traversal

1. Row-wise Traversal

In row-wise traversal, elements of the matrix are accessed row by row.

for (let i = 0; i < rows; i++) {
  for (let j = 0; j < cols; j++) {
    console.log(matrix[i][j] + " ");
  }
}

Example:

1 2 3
4 5 6
7 8 9

Output:

1 2 3 4 5 6 7 8 9

2. Column-wise Traversal

In column-wise traversal, elements are accessed column by column.

for (let j = 0; j < cols; j++) {
  for (let i = 0; i < rows; i++) {
    console.log(matrix[i][j] + " ");
  }
}

Example:

1 2 3
4 5 6
7 8 9

Output:

1 4 7 2 5 8 3 6 9

3. Diagonal Traversal

Diagonal traversal accesses elements along the diagonals of the matrix.

for (let d = 0; d < rows + cols - 1; d++) {
  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      if (i + j === d) {
        console.log(matrix[i][j] + " ");
      }
    }
  }
}

Example Output:

1 2 4 3 5 7 6 8 9

4. Spiral Traversal

Spiral traversal moves in a clockwise or counterclockwise spiral order.

function spiralTraversal(matrix) {
  let result = [];
  while (matrix.length) {
    result = result.concat(matrix.shift());
    matrix.forEach((row) => result.push(row.pop()));
    matrix.reverse().forEach((row) => row.reverse());
  }
  return result;
}

Example Output:

1 2 3 6 9 8 7 4 5

5. Zig-Zag Traversal

Zig-zag traversal moves in a diagonal wave-like pattern.

function zigzagTraversal(matrix) {
  let rows = matrix.length;
  let cols = matrix[0].length;

  let result = [];
  let direction = 1;

  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      let index = direction > 0 ? j : cols - j - 1;
      result.push(matrix[i][index]);
    }
    direction *= -1;
  }

  return result;
}

Example Output:

1 2 3 6 5 4 7 8 9

Applications of Matrix Traversal