如何在网格周围创建边界

how to create a boundry around a grid

本文关键字:创建 边界 周围 网格      更新时间:2023-10-16

程序应该输出一个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个边然而一个人能做的最简单的盒子包含两行,因为我们可以取盒子的高度为零-或无穷小。在代码中,你至少需要2行来创建一个框。

一样:

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

因此创建一个像这样的框:

000000000000000
011111111111110
000000000000000

你注意到了什么?第一行和最后一行都是0。中间行的第一个和最后一个元素都是0,该行的其他元素都是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;
}