0

该程序应该输出一个 12x24 的网格,所有外部线输出 0,内部线输出 1

这是我为了让第一列和第一行输出0而尝试的:

#include <iostream>

using namespace std;
#define N 24
// print:
//
// Prints the simulation matrix M as spaces, *'s, and T's.
//
void print(int M[][N], int ROWS, int COLS)
{
// YOU MUST IMPLEMENT THIS:
}
//
// fill:
//
// Fills the simulation matrix such that the boundary rows
// and columns are empty, the internal area is all trees,
// and one tree is burning at index position (row, col).
//
void fill(int M[][N], int ROWS, int COLS, int row, int col)
{
// YOU MUST IMPLEMENT THIS:

//
// main:
}//
int main()
{
int M[N/2][N];
int ROWS, COLS;
int r, c;
ROWS = sizeof(M) / sizeof(M[0]);
COLS = sizeof(M[0]) / sizeof(M[0][0]);
fill(M, ROWS, COLS, 1, 1);
for(r=0; r< ROWS; r++)
{
for(c=0; c< COLS; c++)
{
    if(ROWS>1)
    {
    M[ROWS][COLS]=1;
    cout<< M[ROWS][COLS];
    }
    else
    {

    M[ROWS][COLS]=0;
    cout<< M[ROWS][COLS];
}
}
cout<< endl;
}

print(M, ROWS, COLS);
return 0; 
}

如何才能做到这一点?

4

1 回答 1

1

首先,问问自己:“我将如何创建一个盒子?” 要创建一个盒子,您需要4 个边但是可以制作的最简单的盒子包含两条线,因为我们可以将盒子的高度设为零或无穷小。在代码中,您至少需要 2 行来制作一个盒子。

像这样:

000000000000000
000000000000000

然而,它没有高度。换句话说,这是一个零高度边框框。

因此要创建一个这样的盒子:

000000000000000
011111111111110
000000000000000

你注意到了什么?第一行和最后一行全为零。并且,中间行的第一个和最后一个元素是零,该行上的所有其他元素都是 1。

进一步扩展:

000000000000000
011111111111110
011111111111110
000000000000000

我们看到了相同的模式——所以这可以扩展到第 n 行的情况。因此,算法是:

  1. 第一行和最后一行都是零。
  2. 对于所有其他行,这些行的第一列和最后一列都为 0。
  3. 其他一切都设置为 1。

因此,在您的情况下:

for(r=0; r< ROWS; r++)
{
    for(c=0; c < COLS; c++)
    {
        if (r == 0 || r == ROWS - 1) {
            M[r][c]=0;
        }
        else if(c == 0 || c == COLS -1) {
            M[r][c]=0;
        }
        else {
            M[r][c]=1;  
        }
        cout<< M[r][c];
    }
    cout << endl;
}
于 2013-03-18T05:09:15.397 回答