알고리즘/codefights

59>spiralNumbers

Diademata 2018. 4. 14. 01:23
반응형

Construct a square matrix with a size N × N containing integers from 1 to N * N in a spiral order, starting from top-left and in clockwise direction.


Example


For n = 3, the output should be


spiralNumbers(n) = [[1, 2, 3],

                    [8, 9, 4],

                    [7, 6, 5]] 


code>>


std::vector<std::vector<int>> spiralNumbers(int n) {

std::vector<std::vector<int>> _list;

for (int i = 0; i < n; i++)

_list.push_back(std::vector<int>(n));

int x = -1, y = 0, idx = 1;

int jump = 1, max = n *n;

while (idx <= max)

{

for (int i = 0; i < n; i++)

{

x += jump;

_list[y][x] = idx++;

}

for (int i = 0; i < n - 1; i++)

{

y += jump;

_list[y][x] = idx++;

}

jump *= -1;

n--;

}

return _list;

}

반응형

'알고리즘 > codefights' 카테고리의 다른 글

1>addTwoDigits  (0) 2018.05.19
60>sudoku  (0) 2018.04.14
58>messageFromBinaryCode  (0) 2018.04.13
57>fileNaming  (0) 2018.04.13
56>digitsProduct  (0) 2018.04.12