CS205

2D Arrays (Matrices)

Explore two-dimensional arrays and learn different traversal patterns. Watch how each traversal visits cells in a specific order.

Row-Major Order
Rows:
Cols:
[0]
[1]
[2]
[3]
[4]
[0]
1
2
3
4
5
[1]
6
7
8
9
10
[2]
11
12
13
14
15
[3]
16
17
18
19
20
Ready to start traversal
Step 0 of 0
Speed:300ms
Unvisited
Current
Visited
Traversal Info

Visits elements row by row, left to right.

Time Complexity
O(m × n)
Matrix Size
4 × 5 = 20 cells
Cells Visited
0 / 20

Key Concepts

  • Row-Major: Standard traversal, row by row. Used in most programming languages for memory layout.
  • Column-Major: Column by column traversal. Used in languages like Fortran and MATLAB.
  • Spiral: Clockwise from outside to inside. Common interview question pattern.
  • Diagonal: Traverses along diagonal lines. Useful for matrix operations and pattern recognition.

Java Syntax

// Declare 2D array
int[][] matrix = new int[rows][cols];

// Initialize with values
int[][] matrix = {
  {1, 2, 3},
  {4, 5, 6},
  {7, 8, 9}
};

// Access element
int value = matrix[row][col];

// Row-major traversal
for (int i = 0; i < rows; i++) {
  for (int j = 0; j < cols; j++) {
    System.out.print(matrix[i][j]);
  }
}

Keyboard Shortcuts

Space Play / Pause
Step Back
Step Forward
R Reset