方形 for 循环图案

Ruu*_*kis 2 java for-loop

我面临着一个我的大脑无法处理的问题!我需要创建一个循环来创建这样的模式:

1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
Run Code Online (Sandbox Code Playgroud)

所以内部的数字越大,但我就是不知道如何创建这样的循环,我的人工智能需要这个循环,这样我就可以为实体创建兴趣区域,所以这不是学校作业,也是我迄今为止尝试过的

for(int i = 0; i < rows; i++){
   for(int j = 0; j < cols; j++){
      System.out.print("?");
   }
   System.out.println();
}
Run Code Online (Sandbox Code Playgroud)

我真的想不出一种方法来获取代表它处于哪个级别的数字!我一直在尝试对自己进行可视化等等,以找出创建这个或根本创建这个的最佳方法。请帮助我和我的大脑免受头痛!:)我想要的是简单的伪代码或任何易于理解的语言的代码(例如java,c ++,c ...)

sth*_*sth 5

你可以这样做:

for(int i = 0; i < rows; i++){
   for(int j = 0; j < cols; j++){
      // The distance to the left, right, top and bottom border:
      int dl = j;
      int dr = cols - (j+1);
      int dt = i;
      int db = rows - (i+1);

      // The distance to the closest border:
      int d = Math.min(Math.min(dl, dr), Math.min(dt, db));

      // Print according number
      System.out.print(d+1);
   }
   System.out.println();
}
Run Code Online (Sandbox Code Playgroud)