🧠
Directional Simulation with Direction Vectors
💡 This approach uses direction vectors to simplify movement logic, reducing code duplication and making the spiral traversal more elegant.
Intuition
Instead of writing separate loops for each direction, use a direction array to cycle through right, down, left, and up movements, changing direction when hitting boundaries or filled cells.
Algorithm
- Initialize an n x n matrix with zeros.
- Define direction vectors for right, down, left, and up movements.
- Start at the top-left cell and move in the current direction.
- If the next cell is out of bounds or already filled, turn right (change direction).
- Continue until all cells are filled.
💡 This approach abstracts direction changes, avoiding repetitive code blocks for each direction.
def generateMatrix(n):
matrix = [[0]*n for _ in range(n)]
directions = [(0,1),(1,0),(0,-1),(-1,0)] # right, down, left, up
dir_idx = 0
row = col = 0
for num in range(1, n*n + 1):
matrix[row][col] = num
dr, dc = directions[dir_idx]
r, c = row + dr, col + dc
if r < 0 or r >= n or c < 0 or c >= n or matrix[r][c] != 0:
dir_idx = (dir_idx + 1) % 4
dr, dc = directions[dir_idx]
r, c = row + dr, col + dc
row, col = r, c
return matrix
# Driver code
if __name__ == '__main__':
n = 3
result = generateMatrix(n)
for row in result:
print(row)
Line Notes
directions = [(0,1),(1,0),(0,-1),(-1,0)]Define movement vectors for right, down, left, up
dir_idx = 0Start moving right initially
for num in range(1, n*n + 1):Fill numbers from 1 to n squared
matrix[row][col] = numAssign current number to current cell
if r < 0 or r >= n or c < 0 or c >= n or matrix[r][c] != 0:Check if next cell is invalid or already filled
dir_idx = (dir_idx + 1) % 4Change direction clockwise
row, col = r, cMove to next valid cell
import java.util.*;
public class SpiralMatrixII {
public static int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}};
int dirIdx = 0;
int row = 0, col = 0;
for (int num = 1; num <= n*n; num++) {
matrix[row][col] = num;
int dr = directions[dirIdx][0], dc = directions[dirIdx][1];
int r = row + dr, c = col + dc;
if (r < 0 || r >= n || c < 0 || c >= n || matrix[r][c] != 0) {
dirIdx = (dirIdx + 1) % 4;
dr = directions[dirIdx][0];
dc = directions[dirIdx][1];
r = row + dr;
c = col + dc;
}
row = r;
col = c;
}
return matrix;
}
public static void main(String[] args) {
int n = 3;
int[][] result = generateMatrix(n);
for (int[] row : result) {
System.out.println(Arrays.toString(row));
}
}
}
Line Notes
int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}};Store direction vectors for spiral movement
int dirIdx = 0;Start moving right
for (int num = 1; num <= n*n; num++)Fill numbers from 1 to n squared
matrix[row][col] = num;Fill current cell with number
if (r < 0 || r >= n || c < 0 || c >= n || matrix[r][c] != 0)Check if next cell is invalid or filled
dirIdx = (dirIdx + 1) % 4;Rotate direction clockwise
row = r; col = c;Move to next cell
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n, 0));
vector<pair<int,int>> directions = {{0,1},{1,0},{0,-1},{-1,0}};
int dirIdx = 0;
int row = 0, col = 0;
for (int num = 1; num <= n*n; num++) {
matrix[row][col] = num;
int dr = directions[dirIdx].first, dc = directions[dirIdx].second;
int r = row + dr, c = col + dc;
if (r < 0 || r >= n || c < 0 || c >= n || matrix[r][c] != 0) {
dirIdx = (dirIdx + 1) % 4;
dr = directions[dirIdx].first;
dc = directions[dirIdx].second;
r = row + dr;
c = col + dc;
}
row = r;
col = c;
}
return matrix;
}
int main() {
int n = 3;
vector<vector<int>> result = generateMatrix(n);
for (auto &row : result) {
for (int val : row) cout << val << ' ';
cout << '\n';
}
return 0;
}
Line Notes
vector<pair<int,int>> directions = {{0,1},{1,0},{0,-1},{-1,0}};Store direction vectors for spiral traversal
int dirIdx = 0;Start moving right
for (int num = 1; num <= n*n; num++)Fill numbers from 1 to n squared
matrix[row][col] = num;Assign current number to current cell
if (r < 0 || r >= n || c < 0 || c >= n || matrix[r][c] != 0)Check if next cell is invalid or already filled
dirIdx = (dirIdx + 1) % 4;Change direction clockwise
row = r; col = c;Move to next valid cell
function generateMatrix(n) {
const matrix = Array.from({ length: n }, () => Array(n).fill(0));
const directions = [[0,1],[1,0],[0,-1],[-1,0]];
let dirIdx = 0;
let row = 0, col = 0;
for (let num = 1; num <= n*n; num++) {
matrix[row][col] = num;
let dr = directions[dirIdx][0], dc = directions[dirIdx][1];
let r = row + dr, c = col + dc;
if (r < 0 || r >= n || c < 0 || c >= n || matrix[r][c] !== 0) {
dirIdx = (dirIdx + 1) % 4;
dr = directions[dirIdx][0];
dc = directions[dirIdx][1];
r = row + dr;
c = col + dc;
}
row = r;
col = c;
}
return matrix;
}
// Driver code
const n = 3;
const result = generateMatrix(n);
result.forEach(row => console.log(row));
Line Notes
const directions = [[0,1],[1,0],[0,-1],[-1,0]];Define direction vectors for spiral movement
let dirIdx = 0;Start moving right
for (let num = 1; num <= n*n; num++)Fill numbers from 1 to n squared
matrix[row][col] = num;Fill current cell with number
if (r < 0 || r >= n || c < 0 || c >= n || matrix[r][c] !== 0)Check if next cell is invalid or already filled
dirIdx = (dirIdx + 1) % 4;Rotate direction clockwise
row = r; col = c;Move to next cell
Each cell is visited exactly once, and direction changes are constant time operations.
💡 For n=10, this means 100 steps, which is efficient and easy to implement.
Interview Verdict: Accepted
This approach is elegant and often preferred for its clean logic and maintainability.