1+ /*
2+ written by Pankaj Kumar.
3+ country:-INDIA
4+ */
5+ typedef long long ll ;
6+ const ll INF=1e18 ;
7+ const ll mod1=1e9 +7 ;
8+ const ll mod2=998244353 ;
9+ // Add main code here
10+
11+ class Solution
12+ {
13+ public:
14+ bool isValid (int i, int j, int n, int m)
15+ {
16+ return !(i < 0 || j < 0 || i >= n || j >= m);
17+ }
18+ vector<vector<int >> spiralMatrixIII (int rows, int cols, int r, int c)
19+ {
20+ vector<vector<int >> ans{{r, c}};
21+ int size = rows * cols, len = 1 ;
22+ int x = r, y = c;
23+ while (ans.size () < size)
24+ {
25+ for (int j = 1 ; j <= len; j++)
26+ {
27+ if (isValid (x, y + j, rows, cols))
28+ ans.push_back ({x, y + j});
29+ }
30+
31+ y += len; // going right;
32+
33+ for (int j = 1 ; j <= len; j++)
34+ {
35+ if (isValid (x + j, y, rows, cols))
36+ ans.push_back ({x + j, y});
37+ }
38+
39+ x += len; // going down;
40+ len++; // increasing length after down in over;
41+
42+ for (int j = 1 ; j <= len; j++)
43+ {
44+ if (isValid (x, y - j, rows, cols))
45+ ans.push_back ({x, y - j});
46+ }
47+
48+ y -= len; // going left;
49+
50+ for (int j = 1 ; j <= len; j++)
51+ {
52+ if (isValid (x - j, y, rows, cols))
53+ ans.push_back ({x - j, y});
54+ }
55+
56+ x -= len; // going up;
57+ len++;
58+ }
59+
60+ return ans;
61+ }
62+ };
0 commit comments