Table of Contents
Example
Algorithm
Output
Home Backend Development C++ Print n x n spiral matrix using C program, using O(1) extra space

Print n x n spiral matrix using C program, using O(1) extra space

Sep 06, 2023 am 11:53 AM

Given a positive integer n, and construct an n x n spiral matrix, using only O(1) extra space in the clockwise direction

A spiral matrix is ​​a matrix that works like a spiral, it will Start from the origin of the circle and rotate in a clockwise direction. So the task is to print the matrix in spiral form using O(1) space starting from 2 → 4 → 6 → 8 → 10 → 12 → 14 → 1 6→ 18.

Below is an example spiral matrix -

使用C程序打印n x n的螺旋矩阵,使用O(1)额外空间

Example

Input: 3
Output:
   9 8 7
   2 1 6
   3 4 1
Copy after login

It becomes easy to solve code with infinite space, but it doesn’t Efficient like an optimal program, or code that is both memory and time efficient. So to maintain the spiral order four loops are used, one each for the upper, right, lower and left corners of the matrix, but if we divide the matrix into two parts, the upper right and lower left corners, we can directly use This concept

< p>For the upper right half,

mat[i][j] = (n-2*x)*(n-2*x)-(i-x)-(j-x)
Copy after login

For the lower left half,

mat[i][j] = (n-2*x-2)*(n-2*x-2) + (i-x) + (j-x)
Copy after login

Note-We are writing for print 2 Program for multiples of matrices

Algorithm

int spiralmatrix(int n)
START
STEP 1: DECLARE i, j, a, b, x
STEP 2: LOOP FOR i = 0 AND i < n AND i++
   LOOP FOR j = 0 AND j < n AND j++
      FIND THE MINIMUM IN (i<j ) AND ASSIGN IT TO a
      FIND THE MINIMUM (n-1-i) < (n-1-j) AND ASSIGN IT TO b
      THEN ASSIGN THE LEAST VALUE FROM a AND b TO x
      IF i <= j THEN,
         PRINT THE VALUE OF 2* ((n-2*x)*(n-2*x) - (i-x) - (j-x))
      ELSE
         PRINT THE VALUE OF 2*((n-2*x-2)*(n-2*x2) + (i-x) + (j-x))
   END LOOP
   PRINT NEWLINE
END LOOP
STOP
Copy after login

Example

#include <stdio.h>
//For n x n spiral matrix
int spiralmatrix(int n){
   int i, j, a, b, x; // x stores the layer in which (i, j)th element exist
   for ( i = 0; i < n; i++){
      for ( j = 0; j < n; j++){
         // Finds minimum of four inputs
         a = ((i<j ? i : j));
         b = ((n-1-i) < (n-1-j) ? (n-1-i) : (n-1-j));
         x = a < b ? a : b;
         // For upper right half
         if (i <= j)
            printf("%d\t ", 2 * ((n-2*x)*(n-2*x) - (i-x) - (j-x)));
            // for lower left half
         else
            printf("%d\t ", 2*((n-2*x-2)*(n-2*x-2) + (i-x) + (j-x)));
      }
      printf("</p><p>");
   }
}
int main(int argc, char const *argv[]){
   int n = 3;
   spiralmatrix(n);
   return 0;
}
Copy after login

Output

If we run the above program then it will generate the following output -

18 16 14
4 2 12
6 8 10
Copy after login

The above is the detailed content of Print n x n spiral matrix using C program, using O(1) extra space. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the types of values ​​returned by c language functions? What determines the return value? What are the types of values ​​returned by c language functions? What determines the return value? Mar 03, 2025 pm 05:52 PM

This article details C function return types, encompassing basic (int, float, char, etc.), derived (arrays, pointers, structs), and void types. The compiler determines the return type via the function declaration and the return statement, enforcing

Gulc: C library built from scratch Gulc: C library built from scratch Mar 03, 2025 pm 05:46 PM

Gulc is a high-performance C library prioritizing minimal overhead, aggressive inlining, and compiler optimization. Ideal for performance-critical applications like high-frequency trading and embedded systems, its design emphasizes simplicity, modul

C language function format letter case conversion steps C language function format letter case conversion steps Mar 03, 2025 pm 05:53 PM

This article details C functions for string case conversion. It explains using toupper() and tolower() from ctype.h, iterating through strings, and handling null terminators. Common pitfalls like forgetting ctype.h and modifying string literals are

What are the definitions and calling rules of c language functions and what are the What are the definitions and calling rules of c language functions and what are the Mar 03, 2025 pm 05:53 PM

This article explains C function declaration vs. definition, argument passing (by value and by pointer), return values, and common pitfalls like memory leaks and type mismatches. It emphasizes the importance of declarations for modularity and provi

Where is the return value of the c language function stored in memory? Where is the return value of the c language function stored in memory? Mar 03, 2025 pm 05:51 PM

This article examines C function return value storage. Small return values are typically stored in registers for speed; larger values may use pointers to memory (stack or heap), impacting lifetime and requiring manual memory management. Directly acc

distinct usage and phrase sharing distinct usage and phrase sharing Mar 03, 2025 pm 05:51 PM

This article analyzes the multifaceted uses of the adjective "distinct," exploring its grammatical functions, common phrases (e.g., "distinct from," "distinctly different"), and nuanced application in formal vs. informal

How do I use algorithms from the STL (sort, find, transform, etc.) efficiently? How do I use algorithms from the STL (sort, find, transform, etc.) efficiently? Mar 12, 2025 pm 04:52 PM

This article details efficient STL algorithm usage in C . It emphasizes data structure choice (vectors vs. lists), algorithm complexity analysis (e.g., std::sort vs. std::partial_sort), iterator usage, and parallel execution. Common pitfalls like

How does the C   Standard Template Library (STL) work? How does the C Standard Template Library (STL) work? Mar 12, 2025 pm 04:50 PM

This article explains the C Standard Template Library (STL), focusing on its core components: containers, iterators, algorithms, and functors. It details how these interact to enable generic programming, improving code efficiency and readability t

See all articles