Given an integer N. Return a N x N matrix such that every aspect (Coordinates(i, j))is having most absolute distinction doable with the adjoining aspect (i.e., (i + 1, j), (i – 1, j), (i, j + 1), (i, j – 1)). Additionally, It ought to include distinct components starting from 1 to N2.
Examples:
Enter: N = 2
Output: 4 1
2 3Enter: N = 3
Output: 1 3 4
9 2 7
5 8 6
Strategy: The issue could be solved primarily based on the next thought:
The distinct numbers don’t exceed N2 – 1, as a result of the minimal distinction between two components is no less than 1, and the most distinction doesn’t exceed N2 – 1 (the distinction between the utmost aspect N2 and the minimal aspect 1).
Observe the under steps to implement the thought:
- Initialize an empty 2D matrix v of dimension N*N and bool examine = true.
- Begin including the weather from 1 to N2 i.e., l and r pointers respectively.
- If examine = true, begin including the weather from the r pointer in reducing order till the row is stuffed and alter the examine = false.
- If examine = false, begin including the weather from the l pointer in rising order till the row is stuffed and alter the examine = true.
- Repeat this till all matrix is stuffed.
Beneath is the implementation of the above strategy:
C++
// C++ Implementation of the above strategy #embrace <bits/stdc++.h> utilizing namespace std; // Operate to create required matrix void findMaximumDistinct(int n, vector<vector<int> >& v) { // l is left pointer and r is // proper pointer int l = 1, r = n * n, t = 0; bool examine = true; // Creating matrix by nested for loop for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Inserting one aspect from // beginning and one aspect // from ending (1 to n^2-1) if (examine == false) { // Inserting the worth // from beginning v[i][j] = l++; examine = true; } else { // Inserting the worth // from ending v[i][j] = r--; // Checking the bool for // alternatingly insertion examine = false; } } // Revrse the current row for // odd row if (i % 2) reverse(v[i].start(), v[i].finish()); } } // Driver Code int principal() { int n = 3; vector<vector<int> > v(n, vector<int>(n)); // Operate name findMaximumDistinct(n, v); // Displaying the matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << v[i][j] << " "; } cout << endl; } return 0; }
Time Complexity: O(n2)
Auxiliary Area: O(n2)