aboutsummaryrefslogtreecommitdiff
path: root/spiral_matrix2.cpp
blob: de119a504ca5e2a23c41b347445f937ab1c2282a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 59. Spiral Matrix II
#include "leetcode.h"

// given a positive integer 'n', generate an n x n 'matrix' filled with
// elements from 1 to 'n^2' in spiral order

class Solution {
public:
  vvd(int) generateMatrix(int n) {
    vvd(int) matrix(n, vector<int>(n));
    int num = 1, row = 0, col = 0, dir = 0;
    vector<int> d_r = {0, 1, 0, -1}, d_c = {1, 0, -1, 0};
    while (num <= n * n) {
      matrix[row][col] = num;
      num++;
      int next_row = row + d_r[dir];
      int next_col = col + d_c[dir];
      if (next_row < 0 || next_row >= n || next_col < 0 || next_col >= n ||
          matrix[next_row][next_col])
        dir = (dir + 1) % 4;
      row += d_r[dir];
      col += d_c[dir];
    }
    return matrix;
  }
};