forked from thundergolfer/interview-with-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspiral.hpp
More file actions
62 lines (53 loc) · 1.52 KB
/
spiral.hpp
File metadata and controls
62 lines (53 loc) · 1.52 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#ifndef SPIRAL_HPP_INCLUDED
#define SPIRAL_HPP_INCLUDED
#include <vector> // std::vector
#include <utility> // std::move
std::vector<unsigned int> spiral(unsigned int height, unsigned int width, int row, int column) {
enum {
Up, Left, Down, Right
} currentDirection = Up;
unsigned int maxLength = 1,
length = 0;
std::vector<unsigned int> visited;
while(visited.size() != height*width) {
if(width >= column && column > 0)
if(height >= row && row > 0)
visited.push_back(column + (row - 1)*width);
switch(currentDirection) {
case Up:
--row;
break;
case Left:
--column;
break;
case Down:
++row;
break;
case Right:
++column;
break;
}
++length;
if(length == maxLength) {
length = 0;
switch(currentDirection) {
case Up:
currentDirection = Left;
break;
case Left:
currentDirection = Down;
++maxLength;
break;
case Down:
currentDirection = Right;
break;
case Right:
currentDirection = Up;
++maxLength;
break;
}
}
}
return std::move(visited);
}
#endif