8 questions. Covers Spiral traversal.
Questions 1 to 5 of 8
cpp #include <algorithm> #include <iostream> #include <utility> #include <vector> using namespace std; using Matrix = vector<vector<int>>; void transpose(Matrix& m) { size_t n = m.size(); for (size_t i = 0; i < n; ++i) { for (size_t j = i + 1; j < n; ++j) { swap(m[i][j], m[j][i]); } } } void reverse_each_row(Matrix& m) { for (auto& row : m) { ranges::reverse(row); } } int main() { Matrix m = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; reverse_each_row(m); transpose(m); cout << m[0][0] << " " << m[0][1] << " " << m[0][2] << " " << m[0][3] << "\n"; }
cpp #include <iostream> #include <utility> #include <vector> using namespace std; int main() { vector<vector<int>> m = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; for (size_t i = 0; i < 3; ++i) { for (size_t j = i + 1; j < 3; ++j) { swap(m[i][j], m[j][i]); } } cout << m[0][1] << " " << m[1][2] << " " << m[2][0] << "\n"; }
cpp #include <iostream> #include <vector> using namespace std; vector<int> spiral(const vector<vector<int>>& g) { vector<int> out; int top = 0; int bottom = static_cast<int>(g.size()) - 1; int left = 0; int right = static_cast<int>(g[0].size()) - 1; while (top <= bottom && left <= right) { for (int c = left; c <= right; c++) { out.push_back(g[top][c]); } top++; for (int r = top; r <= bottom; r++) { out.push_back(g[r][right]); } right--; if (top <= bottom) { for (int c = right; c >= left; c--) { out.push_back(g[bottom][c]); } bottom--; } if (left <= right) { for (int r = bottom; r >= top; r--) { out.push_back(g[r][left]); } left++; } } return out; } int main() { vector<vector<int>> g = {{1, 2, 3}, {4, 5, 6}}; vector<int> v = spiral(g); cout << v[3] << " " << v[4] << " " << v[5] << "\n"; }
Use the arrows to put the steps in order.
3 question(s) left on this page.