void _gen(vector<vector<int> > &matrix, int x, int y, int d) { int n = matrix.size(), m = matrix[0].size(); ans.push_back(matrix[x][y]); visted[x][y] = true; if (ans.size() == n * m) return ; int nx = x + dir[d][0], ny = y + dir[d][1]; if ((0 <= nx && nx < n && 0 <= ny && ny < m) && !visted[nx][ny]) { _gen(matrix, nx, ny, d); } else { d = (d + 1) % 4; _gen(matrix, x + dir[d][0], y + dir[d][1], d); } }
vector<int> spiralOrder(vector<vector<int> > &matrix) { ans.clear(); if (matrix.size() == 0) return ans; visted = vector<vector<bool> >(matrix.size(), vector<bool>(matrix[0].size(), false)); _gen(matrix, 0, 0, 0); return ans; }
TreeNode *sortedListToBST(ListNode *head) { vector<int> vals; for (ListNode *p = head; p; p = p->next) { vals.push_back(p->val); } return _gen(vals, 0, vals.size()); }
void Template::generate(InterpreterMacroAssembler* masm) { // parameter passing TemplateTable::_desc = this; TemplateTable::_masm = masm; // code generation _gen(_arg); masm->flush(); }
void _gen(string &s, int k, vector<vector<bool> > &pali, vector<vector<string>> &ans, vector<string> &now) { if (k == s.size()) { ans.push_back(now); return ; } for (int i = k + 1; i <= s.size(); ++i) { if (pali[k][i]) { now.push_back(s.substr(k, i - k)); _gen(s, i, pali, ans, now); now.pop_back(); } } }
vector<vector<string>> partition(string s) { int n = s.size(); vector<vector<bool> > pali(s.size(), vector<bool> (s.size() + 1, false)); for (int i = 0; i < n; ++i) { pali[i][i] = pali[i][i + 1] = true; } for (int len = 2; len <= n; ++len) { for (int i = 0; i + len <= n; ++i) { int j = i + len; if (s[i] == s[j - 1] && pali[i + 1][j - 1]) { pali[i][j] = true; } } } vector<vector<string> > ans; vector<string> now; _gen(s, 0, pali, ans, now); return ans; }
void Labyrinth::gen() { if (!m_gen) { _gen(); } }