Graph Theory37 sections · 1633 units
Open in Course

LeetCode 1091 Shortest Path in Binary Matrix - Direction Arrays

A Pro Tip

Instead of writing 88 separate if-statements for each direction, use direction arrays. Store the row and column offsets:

dr := [-1, -1, -1, 0, 0, 1, 1, 1]
dc := [-1, 0, 1, -1, 1, -1, 0, 1]

These represent all 88 directions: up-left, up, up-right, left, right, down-left, down, down-right. Loop through them:

for i from 0 to 7:
    nr := r + dr[i]
    nc := c + dc[i]
    if (nr, nc) is valid:
        process neighbor

For 44-directional movement, use dr = [-1, 0, 1, 0] and dc = [0, 1, 0, -1]. This pattern keeps your code clean and reduces bugs.