From 1b681502fbec5765514079e76f5da767aa8a5171 Mon Sep 17 00:00:00 2001 From: Yangshun Date: Wed, 29 Jul 2026 17:01:16 +0800 Subject: [PATCH] contents: add matrix index conversion tip Document how to translate between flattened indices and matrix coordinates so readers can apply one-dimensional algorithms such as binary search to matrices. Closes #689 --- apps/website/contents/algorithms/matrix.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/apps/website/contents/algorithms/matrix.md b/apps/website/contents/algorithms/matrix.md index 8866fb66..58128fec 100644 --- a/apps/website/contents/algorithms/matrix.md +++ b/apps/website/contents/algorithms/matrix.md @@ -50,6 +50,23 @@ Copying a matrix in Python is: copied_matrix = [row[:] for row in matrix] ``` +### Converting between 1D and 2D indices + +An `m x n` matrix can be treated as a one-dimensional array with `m * n` elements. Given a zero-based index in that array, divide it by the number of columns to get the row and use the remainder to get the column: + +```py +row = index // num_columns +col = index % num_columns +``` + +To convert a row and column back into a one-dimensional index: + +```py +index = row * num_columns + col +``` + +This technique can be useful when applying algorithms such as binary search to a matrix. + ### Transposing a matrix The transpose of a matrix is found by interchanging its rows into columns or columns into rows.