企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 创建具有 O 和 X 的交替矩形的矩阵 > 原文: [https://www.geeksforgeeks.org/create-a-matrix-with-alternating-rectangles-of-0-and-x/](https://www.geeksforgeeks.org/create-a-matrix-with-alternating-rectangles-of-0-and-x/) 编写代码,输入两个数字 m 和 n,并创建一个大小为 mxn(m 行和 n 列)的矩阵,其中每个元素均为 X 或 0。 Xs 和 0s 必须交替填充,矩阵应具有 Xs 的最外面的矩形,然后是 0s 的矩形,然后是 Xs 的矩形,依此类推。 **示例**: ``` Input: m = 3, n = 3 Output: Following matrix X X X X 0 X X X X Input: m = 4, n = 5 Output: Following matrix X X X X X X 0 0 0 X X 0 0 0 X X X X X X Input: m = 5, n = 5 Output: Following matrix X X X X X X 0 0 0 X X 0 X 0 X X 0 0 0 X X X X X X Input: m = 6, n = 7 Output: Following matrix X X X X X X X X 0 0 0 0 0 X X 0 X X X 0 X X 0 X X X 0 X X 0 0 0 0 0 X X X X X X X X ``` ***我们强烈建议最小化浏览器,然后自己尝试。*** 在 Shreepartners Gurgaon 的校园招聘中提出了这个问题。 我遵循以下方法。 **1)**使用[代码以螺旋形式](https://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/)打印矩阵。 **2)**而不是打印数组,而是在数组中插入元素“ X”或“ 0”。 以下是上述方法的实现。 ## C++ ```cpp #include <stdio.h> // Function to print alternating rectangles of 0 and X void fill0X(int m, int n) {     /*  k - starting row index         m - ending row index         l - starting column index         n - ending column index         i - iterator    */     int i, k = 0, l = 0;     // Store given number of rows and columns for later use     int r = m, c = n;     // A 2D array to store the output to be printed     char a[m][n];     char x = 'X'; // Iniitialize the character to be stoed in a[][]     // Fill characters in a[][] in spiral form. Every iteration fills     // one rectangle of either Xs or Os     while (k < m && l < n)     {         /* Fill the first row from the remaining rows */         for (i = l; i < n; ++i)             a[k][i] = x;         k++;         /* Fill the last column from the remaining columns */         for (i = k; i < m; ++i)             a[i][n-1] = x;         n--;         /* Fill the last row from the remaining rows */         if (k < m)         {             for (i = n-1; i >= l; --i)                 a[m-1][i] = x;             m--;         }         /* Print the first column from the remaining columns */         if (l < n)         {             for (i = m-1; i >= k; --i)                 a[i][l] = x;             l++;         }         // Flip character for next iteration         x = (x == '0')? 'X': '0';     }     // Print the filled matrix     for (i = 0; i < r; i++)     {         for (int j = 0; j < c; j++)             printf("%c ", a[i][j]);         printf("\n");     } } /* Driver program to test above functions */ int main() {     puts("Output for m = 5, n = 6");     fill0X(5, 6);     puts("\nOutput for m = 4, n = 4");     fill0X(4, 4);     puts("\nOutput for m = 3, n = 4");     fill0X(3, 4);     return 0; } ```