878902. Print Square wall
Basic
Print Square Wall
Summary
This problem involves printing a square wall with dimensions n x n. The task is to print the wall in an ascending order, where each row and column should be printed in ascending order. This problem requires understanding of algorithms for solving problems related to arrays or matrices.
Detailed Explanation
To solve this problem, we can start by initializing an array of size n x n with all elements set to 0. Then, we can iterate over the array from top-left to bottom-right (or vice versa) and fill in the elements with values starting from 1.
Here is a step-by-step breakdown:
- Initialize an array
arrof size n x n with all elements set to 0. - Iterate over the array using two nested loops, where the outer loop represents rows and the inner loop represents columns.
- For each element at position
(i, j), fill in the value asj + i * n - (n - 1) / 2. This ensures that the values are filled in ascending order for both rows and columns.
Here is an ASCII art diagram to illustrate this:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
Time complexity: O(n^2) Space complexity: O(1)
Optimized Solutions
Java
public class Main {
public static void printSquareWall(int n) {
int[][] arr = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = j + i * n - (n - 1) / 2;
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
printSquareWall(5);
}
}