|
| 1 | +/* |
| 2 | +Problem: Number Spiral (CSES Problem Set) |
| 3 | +Link: https://cses.fi/problemset/task/1071/ |
| 4 | +Topic: Math / Pattern Recognition |
| 5 | +
|
| 6 | +Description: |
| 7 | +Given coordinates (y, x) in an infinite number spiral, find the value at that position. |
| 8 | +The spiral grows outwards starting from 1 at (1,1). |
| 9 | +
|
| 10 | +Example spiral pattern: |
| 11 | + 1 2 9 10 25 |
| 12 | + 4 3 8 11 24 |
| 13 | + 5 6 7 12 23 |
| 14 | + 16 15 14 13 22 |
| 15 | + 17 18 19 20 21 |
| 16 | +
|
| 17 | +Approach: |
| 18 | +- The maximum of (x, y) determines which square layer the cell belongs to. |
| 19 | +- The last number of each layer (n) is always n^2. |
| 20 | +- Depending on whether n is even or odd, the numbering direction differs: |
| 21 | + - Even layers fill top-to-bottom. |
| 22 | + - Odd layers fill left-to-right. |
| 23 | +- Use this pattern to directly calculate the value at (x, y) in O(1) time. |
| 24 | +
|
| 25 | +Time Complexity: O(1) |
| 26 | +Space Complexity: O(1) |
| 27 | +*/ |
| 28 | + |
| 29 | +#include <bits/stdc++.h> |
| 30 | +using namespace std; |
| 31 | + |
| 32 | +long long numberSpiralValue(long long x, long long y) { |
| 33 | + if (x == 1 && y == 1) return 1; |
| 34 | + |
| 35 | + long long layer = max(x, y); |
| 36 | + long long base = (layer - 1) * (layer - 1); |
| 37 | + |
| 38 | + if (layer % 2 == 0) { // even layer |
| 39 | + if (y == layer) |
| 40 | + return base + x; |
| 41 | + else |
| 42 | + return base + layer + (layer - y); |
| 43 | + } |
| 44 | + else { // odd layer |
| 45 | + if (x == layer) |
| 46 | + return base + y; |
| 47 | + else |
| 48 | + return base + layer + (layer - x); |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +int main() { |
| 53 | + vector<pair<long long, long long>> tests = { |
| 54 | + {2, 3}, // Expected output: 8 |
| 55 | + {1, 1}, // Expected output: 1 |
| 56 | + {4, 2}, // Expected output: 15 |
| 57 | + {3, 5} // Expected output: 27 |
| 58 | + }; |
| 59 | + |
| 60 | + for (auto [y, x] : tests) { |
| 61 | + cout << "Input (y=" << y << ", x=" << x << ") -> Output: " |
| 62 | + << numberSpiralValue(x, y) << endl; |
| 63 | + } |
| 64 | + |
| 65 | + return 0; |
| 66 | +} |
0 commit comments