spiral print a 2d matrix.

PHOTO EMBED

Fri Jun 28 2024 06:07:11 GMT+0000 (Coordinated Universal Time)

Saved by @vishnu_jha #c++ #dsa #2darray #spiralprint

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;
}
content_copyCOPY

https://youtu.be/1CdolnvxLs0