Skip to main content

Command Palette

Search for a command to run...

2D Arrays - Create A Matrix With Alternating X And 0

Published
1 min read
2D Arrays - Create A Matrix With Alternating X And 0
N

I am Nirbhay Singh , I am starting this blog to document my coding journey of becoming a software developer and to get my first $ 100k offer .

Create A Matrix With Alternating X And 0

https://www.codingninjas.com/studio/problems/create-a-matrix-with-alternating-x-and-0_981321?leftPanelTabValue=PROBLEM

Hint:

  1. Create an array ['X', '0'];

  2. Declare a variable 'ind' and initialize it 0.

  3. Fill the ans matrix with 'arr[ind]', and after completing on rectangle

    • Do, ind = !ind , it will keep on changing simultaneously.
  4. How to iterate,

    • To itertate through 0th row ans n-1th row, only column number will change.

    • Similary to iterate through 0th col and m-1th col, only row number will change.

Code:

#include <bits/stdc++.h> 
vector<vector<char>> constructMatrix(int n, int m)
{
    //    Write your code here.

    vector<vector<char>> ans(n, vector<char>(m,'X'));

    if(n<=2 || m<=2){
        return ans;
    }
    char arr[] = {'X','0'};

    int ind = 0;

    int it1 = 0;
    int mid1 = (n-1)/2;

    int it2 = 0;
    int mid2 = (m-1)/2;

    while(it1<=mid1 && it2<=mid2){

        int row = 0+it1;
        int col = 0+it2;

        for(int i=row;i<n-it1;i++){
            ans[i][col] = arr[ind];
            ans[i][m-1-it2] = arr[ind];
        }

        for(int i=col;i<m-it2;i++){
            ans[row][i] = arr[ind];
            ans[n-1-it1][i] = arr[ind];
        }

        ind = !ind;
        it1++;
        it2++;
    }
    return ans;
}

DSA prep

Part 10 of 22

This series is specifically to document and share my learning of Data Structure and Algorithms and building the programmers intuition to solve a problem through coding and getting my first job as SDE.

Up next

Binary Trees - Maximum Sum Path Of A Binary Tree

Maximum Sum Path Of A Binary Tree Problem Link: https://www.codingninjas.com/studio/problems/maximum-sum-path-of-a-binary-tree_1214968 https://leetcode.com/problems/binary-tree-maximum-path-sum/ Hint: https://www.loom.com/share/c17cd6b7d58a47f389...

More from this blog

Daily Code by Nirbhay

74 posts

Hey, this is Nirbhay. I started this blog to document my journey of learning to code and get my first $100k offer. I'll be sharing the things related to DSA, backend development, devops and many more.