> For the complete documentation index, see [llms.txt](https://dsa-cpp.gitbook.io/nafees/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dsa-cpp.gitbook.io/nafees/arrays/2-d-arrays.md).

# 2-D Arrays

{% hint style="warning" %}
Dynamically 2-D Array Allocation&#x20;

```cpp
int **arr = new int*[rows];
    for (int i = 0; i < rows; i++){
        arr[i] = new int[cols];
    }
// releasing memory 
    for (int i = 0; i < rows; i++){
        delete [] arr[i];
    }
    delete []arr;
```

{% endhint %}

{% code title="Numbers of Rows & Columns in 2d" %}

```cpp
int arr[][3] = { { 1, 2, 3 },
                 { 4, 5, 6 },
                 { 7, 8, 9 } };
    
    int total_Elements = sizeof(arr)/sizeof(int); // 36 / 4 = 9
    cout << "Total Number of elements are: " << total_Elements << endl; 

    int rows = sizeof(arr)/sizeof(arr[0]);  // 36 / 12 = 3

    int cols = sizeof(arr[0])/sizeof(int);  // 12 / 4 = 3
    
    cout << "No of Rows are: "   << rows << endl;
    cout << "No of Columns are: "<< cols << endl;

```

{% endcode %}

{% hint style="success" %}

```cpp
if(largest < sum){
     largest = sum;
     largest_row/colum_index = i;
}
```

{% endhint %}

### `Q1:`  Row-Wise Sum&#x20;

{% code overflow="wrap" %}

```cpp
void RowWiseSum(int arr[][4], int row, int col){
    int largest = INT_MIN;

    cout << "Rows sum!!" << endl;
    for (int i = 0; i < row; i++){
        int sum = 0;
        for (int j = 0; j < col; j++){
            sum += arr[i][j];
        }
        largest = max(largest, sum);
    }
    cout << endl << "Largest Row Sum: " << largest << endl;
}
```

{% endcode %}

### `Q2:`  Column-Wise Sum&#x20;

{% code overflow="wrap" %}

```cpp
void ColWiseSum(int arr[][4], int row, int col){
    int largest = INT_MIN; 

    cout << "Columns sum!!" << endl;
    for (int i = 0; i < col; i++){
        int sum = 0;
        for (int j = 0; j < row; j++){
            sum += arr[j][i]; // arr[row][col];
        }
        largest = max(largest, sum);
    }
    cout << endl << "Largest Columns Sum: " << largest;
}
```

{% endcode %}

### `Q3:`  [Print Like a Wave](https://www.codingninjas.com/studio/problems/print-like-a-wave_893268)

{% code title="Using vector" overflow="wrap" %}

```cpp
vector<int> wavePrint(vector<vector<int>> arr, int nRows, int mCols)
{
    vector <int> ans;
    for(int i = 0; i < mCols; i++){
        if(i%2 == 0) { 
            // top to bottom
            for (int j = 0; j < nRows; j++) {
                ans.push_back(arr[j][i]);
            }
        } 
        else {
            // bottom to top
            for (int j = nRows-1; j >= 0; j--) {
                ans.push_back(arr[j][i]);
            }
        }
    }
    return ans;
}

// T.C = O(nRows*mCols)
```

{% endcode %}

{% code title="Using  Array" %}

```cpp
#include <iostream>
using namespace std;

void print(int arr[][3], const int rows, const int cols) {
    for (int i = 0; i < cols; i++) {
        if(i%2 == 0) {
            for (int j = 0; j < rows; j++) {
                cout << arr[j][i] << " ";
            }
        }
        else{
            for (int j = rows-1; j >= 0; j--) {
                cout << arr[j][i] << " ";
            }
        }
    }
}

int main() {
    int arr[][3] = { { 1, 2, 3 },
                     { 4, 5, 6 },
                     { 7, 8, 9 } };
    int rows = sizeof(arr)/sizeof(arr[0]);
    int cols = sizeof(arr[0])/sizeof(int);
    print(arr, rows, cols); // 1 4 7 8 5 2 3 6 9
}
```

{% endcode %}

### `Q4:`  [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/description/)

{% code overflow="wrap" %}

```cpp
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        
        int SR = 0;
        int SC = 0;
        
        int ER = matrix.size()-1;
        int EC = matrix[0].size()-1;
        
        int count = 0;
        int total = matrix.size() *  matrix[0].size();

        vector<int> ans; 

        while(count < total) {
        
            for(int i = SC; count < total && i <= EC; i++, count++) 
                ans.push_back(matrix[SR][i]);

            SR++;

            for(int i = SR; count < total && i <= ER; i++, count++) 
                ans.push_back(matrix[i][EC]);

            EC--;
            
            for(int i = EC; count < total && i >= SC; i--, count++) 
                ans.push_back(matrix[ER][i]);

            ER--;

            for(int i = ER; count < total && i >= SR; i--, count++) 
                ans.push_back(matrix[i][SC]);
            
            SC++;
        }
        return ans;
    }
};
```

{% endcode %}

## `Q5:`  Transpose of a Matrix

{% code title="using single array" %}

```cpp
#include <iostream>
using namespace std;

int** transposeOFMatrix(int arr[][2], const int rows, const int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < i; j++) { //  ignoring diagonals 
            swap(arr[i][j], arr[j][i]);
        }
    }
}

int main() {
    int arr[][2] = { {1, 2}, {3, 4}, {5, 6}};                     
    int rows = sizeof(arr)/sizeof(arr[0]);
    int cols = sizeof(arr[0])/sizeof(int);
    transposeOFMatrix(arr, rows, cols); 

    for (int i = 0; i < cols; i++) {
        for (int j = 0; j < rows; j++) {
            cout << arr[i][j] << " ";
        } cout << endl;
    }

    return 0;
}
```

{% endcode %}

{% code title="phatt gya nahh hahaha" %}

```cpp
#include <iostream>
using namespace std;

int** transposeOFMatrix(int arr[][2], const int rows, const int cols) {
    
    int **temp = new int*[cols];
    *temp = new int[rows];

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            temp[j][i] = arr[i][j];
        }
    }

    return temp;
}

int main() {
    int arr[][2] = { {1, 2}, {3, 4}, {5, 6}};
                     
    int rows = sizeof(arr)/sizeof(arr[0]);
    int cols = sizeof(arr[0])/sizeof(int);

   int **ptr = transposeOFMatrix(arr, rows, cols); 

    for (int i = 0; i < cols; i++) {
        for (int j = 0; j < rows; j++) {
            cout << ptr[i][j] << " ";
        } cout << endl;
    }

    // deallocating dynamic memory
    for (int i = 0; i < rows; i++) {
        delete[] ptr[i];
    }
    delete[] ptr;
    return 0;
}
```

{% endcode %}

## `Q6:`  [Rotate Image](https://leetcode.com/problems/rotate-image/)

### [Dry Run](https://drive.google.com/file/d/1-SRsGbs9zuu7Odzb-Tyx0bZ2-8UpoHBG/view?usp=sharing)

```cpp
/*
   Steps to rotate image
      - Transpose matrix --> ignoring diagonal elements while swapping
      - Swap the columns
 */
#include <iostream>
using namespace std;

void rotateby90(int arr[][3], const int rows, const int cols) {
    
    // transpose
    for (int i = 0; i < 3; i++) {
    
        for (int j = 0; j < i; j++) { // ignoring diagonals index(0 0, 1 1, 2 2)
            swap(arr[i][j], arr[j][i]);
        }
    }
    
    // swap columns of each row
    for (int i = 0; i < rows; i++) {
        int s = 0;
        int e = cols-1;
        while (s <= e) {
            swap(arr[i][s++], arr[i][e--]);
        }
    }

}

int main() {
    int arr[][3] = { { 1, 2, 3 },
                     { 4, 5, 6 },
                     { 7, 8, 9 } };                
    int rows = sizeof(arr)/sizeof(arr[0]);
    int cols = sizeof(arr[0])/sizeof(int);

    rotateby90(arr, rows, cols); 
    
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << arr[i][j] << " ";
        } cout << endl;   
    }   
}
```

## `Q7:`   [Jagged Array](https://media.geeksforgeeks.org/wp-content/uploads/20200131134104/Jagged-Array.jpg)

```cpp
#include<iostream>
using namespace std;

const int MAX = 100;

int main(){
    int Rows;
    cout << "Rows: "; cin >> Rows;

    // creating 2-d array
    int **arr = new int *[Rows];
    int Cols[MAX];

    for (int i = 0; i < Rows; i++){
        cout << "Enter Colms for " << i+1 << ": "; cin >> i[Cols];
        arr[i] = new int[Cols[i]];
    }
    
    cout << "Enter Elements !!" << endl;
    for (int i = 0; i < Rows; i++){
        for (int j = 0; j < i[Cols]; j++){
            cin >> i[arr][j];
        }
    }
    
    cout << " Your Jagged Array!!" << endl;
    for (int i = 0; i < Rows; i++){
        for (int j = 0; j < i[Cols]; j++){
            cout << i[arr][j] << " "; 
        }cout << endl;
    }
}
```

## `Q8:`   Addition of 2 Matrix

```cpp
#include <iostream>
using namespace std;

int** addition(int a[][2], int b[][2], int rows, int cols) {
    int **temp = new int*[rows];
    *temp = new int[cols];

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            temp[i][j] = a[i][j] + b[i][j];
        }
    }
    return temp;
}

int main() {

    int a[2][2] = { { 1,  2}, 
                    {-1, -2} };
    int b[2][2] = { { 3,  4}, 
                    {-3, -4} };
    
    int** ptr = addition(a, b, 2, 2);

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            cout << ptr[i][j] << " ";
        }cout << endl;
    }
    
    for (int i = 0; i < 2; i++) {
        delete[] ptr[i];
    }
    delete[] ptr;
    return 0;    
}
```

## `Q9:`  Multiplication of a matrix

```cpp
#include <iostream>
using namespace std;

// Two matrices A and B are said to be conformable for the product AB if the number
// of columns of A is equal to the number of rows of B.

int main() {
    int a[][3] = { {1, 2, 3},
                   {4, 5, 6} };
    int b[][2] = { {1, 2},
                   {3, 4},
                   {5, 6} };
                   
    int c[2][2] = {0};

    for (int i = 0; i < 2; i++) {
        for (int k = 0; k < 2; k++){
            for (int j = 0; j < 3; j++) {
                c[i][k] += a[i][j] * b[j][k];
            }
        }
    }
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            cout << c[i][j] << " ";
        }cout << endl;
    }
    return 0;
}
```

## `Q10:`   Reverse 2d array&#x20;

```cpp
#include <iostream>
using namespace std;

int main() {
    int arr[][3] = { {1, 2, 3},
                     {4, 5, 6},
                     {7, 8, 9} };
                     
    int row = sizeof(arr)/sizeof(arr[0]);
    int col = sizeof(arr[0])/sizeof(int);
    
    for (int i = 0; i < row; i++) {
        int s = 0;
        int e = col-1;

        while (s <= e) {
            swap(arr[i][s++], arr[i][e--]);
        }
    }
    
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            cout << arr[i][j] << " ";
        }cout << endl;
    }
    return 0;
}
```

## `Q11:` [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/)

```cpp
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int SR = 0;
        int SC = 0;
        
        int ER = n-1;
        int EC = n-1;
        
        int count = 1;
        int total = n*n;

        vector<vector<int>> matrix(n, vector<int>(n)); 
        
        while(count <= total) {

            for(int i = SC; count <= total && i <= EC; i++) 
                matrix[SR][i] = count++;
             
            SR++;

            for(int i = SR; count <= total && i <= ER; i++) 
                matrix[i][EC] = count++;
             
            EC--;
            
            for(int i = EC; count <= total && i >= SC; i--) 
                matrix[ER][i] = count++;
            
            ER--;
            
            for(int i = ER; count <= total && i >= SR; i--) 
                matrix[i][SC] =count++;
                
            SC++;
        }
        return matrix;
    }
};
```

## `Q12:` [Spiral Matrix IV](https://leetcode.com/problems/spiral-matrix-iv/)

```cpp

class Solution {
public:
    vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) {
        int SR = 0;
        int SC = 0;
        
        int ER = m-1;
        int EC = n-1;

        vector<vector<int>> matrix(m, vector<int>(n, -1));
        
        while(head != nullptr) {

            for(int i = SC; head != nullptr && i <= EC; i++, head = head -> next) 
                matrix[SR][i] = head -> val;
            
            SR++;

            for(int i = SR; head != nullptr && i <= ER; i++, head = head -> next) 
                matrix[i][EC] = head -> val;
             
            EC--;
            
            for(int i = EC; head != nullptr&& i >= SC; i--, head = head -> next) 
                matrix[ER][i] = head -> val;

            ER--;
            
            for(int i = ER; head != nullptr && i >= SR; i--, head = head -> next) 
                matrix[i][SC] = head -> val;
            
            SC++;
        }
        return matrix;
    }
};
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dsa-cpp.gitbook.io/nafees/arrays/2-d-arrays.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
