Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
You are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter).
Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance. You may return the answer in any order that satisfies this condition.
The distance between two cells (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|.
Example 1:
Input: rows = 1, cols = 2, rCenter = 0, cCenter = 0 Output: [[0,0],[0,1]] Explanation: The distances from (0, 0) to other cells are: [0,1]
Example 2:
Input: rows = 2, cols = 2, rCenter = 0, cCenter = 1 Output: [[0,1],[0,0],[1,1],[1,0]] Explanation: The distances from (0, 1) to other cells are: [0,1,1,2] The answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct.
Example 3:
Input: rows = 2, cols = 3, rCenter = 1, cCenter = 2 Output: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]] Explanation: The distances from (1, 2) to other cells are: [0,1,1,2,2,3] There are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]].
Constraints:
1 <= rows, cols <= 1000 <= rCenter < rows0 <= cCenter < colsProblem summary: You are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter). Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance. You may return the answer in any order that satisfies this condition. The distance between two cells (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Math
1 2 0 0
2 2 0 1
2 3 1 2
cells-in-a-range-on-an-excel-sheet)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1030: Matrix Cells in Distance Order
class Solution {
public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
Deque<int[]> q = new ArrayDeque<>();
q.offer(new int[] {rCenter, cCenter});
boolean[][] vis = new boolean[rows][cols];
vis[rCenter][cCenter] = true;
int[][] ans = new int[rows * cols][2];
int[] dirs = {-1, 0, 1, 0, -1};
int idx = 0;
while (!q.isEmpty()) {
for (int n = q.size(); n > 0; --n) {
var p = q.poll();
ans[idx++] = p;
for (int k = 0; k < 4; ++k) {
int x = p[0] + dirs[k], y = p[1] + dirs[k + 1];
if (x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y]) {
vis[x][y] = true;
q.offer(new int[] {x, y});
}
}
}
}
return ans;
}
}
// Accepted solution for LeetCode #1030: Matrix Cells in Distance Order
func allCellsDistOrder(rows int, cols int, rCenter int, cCenter int) (ans [][]int) {
q := [][]int{{rCenter, cCenter}}
vis := make([][]bool, rows)
for i := range vis {
vis[i] = make([]bool, cols)
}
vis[rCenter][cCenter] = true
dirs := [5]int{-1, 0, 1, 0, -1}
for len(q) > 0 {
for n := len(q); n > 0; n-- {
p := q[0]
q = q[1:]
ans = append(ans, p)
for k := 0; k < 4; k++ {
x, y := p[0]+dirs[k], p[1]+dirs[k+1]
if x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y] {
vis[x][y] = true
q = append(q, []int{x, y})
}
}
}
}
return
}
# Accepted solution for LeetCode #1030: Matrix Cells in Distance Order
class Solution:
def allCellsDistOrder(
self, rows: int, cols: int, rCenter: int, cCenter: int
) -> List[List[int]]:
q = deque([[rCenter, cCenter]])
vis = [[False] * cols for _ in range(rows)]
vis[rCenter][cCenter] = True
ans = []
while q:
for _ in range(len(q)):
p = q.popleft()
ans.append(p)
for a, b in pairwise((-1, 0, 1, 0, -1)):
x, y = p[0] + a, p[1] + b
if 0 <= x < rows and 0 <= y < cols and not vis[x][y]:
vis[x][y] = True
q.append([x, y])
return ans
// Accepted solution for LeetCode #1030: Matrix Cells in Distance Order
struct Solution;
impl Solution {
fn all_cells_dist_order(r: i32, c: i32, r0: i32, c0: i32) -> Vec<Vec<i32>> {
let mut cells: Vec<Vec<i32>> = vec![];
for i in 0..r {
for j in 0..c {
cells.push(vec![i, j]);
}
}
cells.sort_unstable_by_key(|v| (v[0] - r0).abs() + (v[1] - c0).abs());
cells
}
}
#[test]
fn test() {
let r = 1;
let c = 2;
let r0 = 0;
let c0 = 0;
let res: Vec<Vec<i32>> = vec_vec_i32![[0, 0], [0, 1]];
assert_eq!(Solution::all_cells_dist_order(r, c, r0, c0), res);
let r = 2;
let c = 2;
let r0 = 0;
let c0 = 1;
let res: Vec<Vec<i32>> = vec_vec_i32![[0, 1], [0, 0], [1, 1], [1, 0]];
assert_eq!(Solution::all_cells_dist_order(r, c, r0, c0), res);
let r = 2;
let c = 3;
let r0 = 1;
let c0 = 2;
let res: Vec<Vec<i32>> = vec_vec_i32![[1, 2], [0, 2], [1, 1], [0, 1], [1, 0], [0, 0]];
assert_eq!(Solution::all_cells_dist_order(r, c, r0, c0), res);
}
// Accepted solution for LeetCode #1030: Matrix Cells in Distance Order
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1030: Matrix Cells in Distance Order
// class Solution {
// public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {
// Deque<int[]> q = new ArrayDeque<>();
// q.offer(new int[] {rCenter, cCenter});
// boolean[][] vis = new boolean[rows][cols];
// vis[rCenter][cCenter] = true;
// int[][] ans = new int[rows * cols][2];
// int[] dirs = {-1, 0, 1, 0, -1};
// int idx = 0;
// while (!q.isEmpty()) {
// for (int n = q.size(); n > 0; --n) {
// var p = q.poll();
// ans[idx++] = p;
// for (int k = 0; k < 4; ++k) {
// int x = p[0] + dirs[k], y = p[1] + dirs[k + 1];
// if (x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y]) {
// vis[x][y] = true;
// q.offer(new int[] {x, y});
// }
// }
// }
// }
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.