Common 2D Array Patterns
Part of the Logic & Flow section of Coddy's Java journey — lesson 8 of 59.
Certain patterns often appear when working with 2D arrays. Recognizing these patterns can help you solve problems more efficiently. Here are a few common patterns:
Diagonal Traversal
Accessing elements where the row index equals the column index (matrix[i][i]) gives you the main diagonal. For the anti-diagonal, the sum of the row and column indices equals the size of the array minus 1 (matrix[i][size - 1 - i]).
For example:
1 2 3
4 5 6
7 8 9Traverse through main diagonal (matrix[i][i]): 1, 5, 9
Traverse through anti-diagonal (matrix[i][size - 1 - i]): 3, 5, 7
Border Traversal
To traverse the border elements, you keep one index constant (0 or size - 1) while iterating over the other.
To access the top border, you iterate over columns with the row index fixed at 0.
For example:
1 2 3 4
5 6 7 8
9 10 11 12border elements: 1, 2, 3, 4, 8, 12, 11, 10, 9, 5 (all except 6 and 7)
Challenge
EasyCreate a method named printPatterns that takes a square 2D array of integers (matrix) as input and prints the following patterns:
- Main Diagonal: Print all elements where the row index equals the column index.
- Anti-Diagonal: Print all elements where the sum of the row and column indices equals the size of the matrix minus 1.
- Borders: Print the elements of the top, bottom, left, and right borders of the matrix.
The output should look like this:
Main Diagonal: 1 6 11 16
Anti-Diagonal: 4 7 10 13
Top Border: 1 2 3 4
Bottom Border: 13 14 15 16
Left Border: 1 5 9 13
Right Border: 4 8 12 16Cheat sheet
Common 2D array traversal patterns:
Diagonal Traversal
Main diagonal: matrix[i][i] (row index equals column index)
Anti-diagonal: matrix[i][size - 1 - i] (sum of row and column indices equals size - 1)
1 2 3
4 5 6
7 8 9Main diagonal: 1, 5, 9
Anti-diagonal: 3, 5, 7
Border Traversal
Keep one index constant (0 or size - 1) while iterating over the other:
- Top border: row = 0, iterate columns
- Bottom border: row = size - 1, iterate columns
- Left border: column = 0, iterate rows
- Right border: column = size - 1, iterate rows
Try it yourself
// Write your code only inside the class. Do not write main() or any code outside this class.
class PrintPatterns {
public static void printPatterns(int[][] matrix) {
// Write your code here
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap