vector<int> spiralPrint(vector<vector<int>> v, int r, int c) { vector<int> ans; int count = 0; ; int total = r * c; int startingRow = 0; int endingRow = r - 1; int startingCol = 0; int endingCol = c - 1; while (count < total) { // print starting row for (int i = startingCol; i <= endingCol && count < total; i++) { ans.push_back(v[startingRow][i]); count++; } startingRow++; // printing ending col for (int i = startingRow; i <= endingRow && count < total; i++) { ans.push_back(v[i][endingCol]); count++; } endingCol--; // printing ending row for (int i = endingCol; i >= startingCol && count < total; i--) { ans.push_back(v[endingRow][i]); count++; } endingRow--; // printing starting col for (int i = endingRow; i >= startingRow && count < total; i--) { ans.push_back(v[i][startingCol]); count++; } startingCol++; } return ans; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter