Table of contents
Create A Matrix With Alternating X And 0
Problem Link:
Hint:
Create an array ['X', '0'];
Declare a variable 'ind' and initialize it 0.
Fill the ans matrix with 'arr[ind]', and after completing on rectangle
- Do, ind = !ind , it will keep on changing simultaneously.
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;
}