#图解
#代码
##java代码实现
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt(),m=sc.nextInt();
int[][] q=new int[n][m];
//偏移量
int[] dx={-1,0,1,0};
int[] dy={0,1,0,-1};
//初始化条件,d=1代表往右走
int x=0,y=0,d=1;
for(int i=1;i<=n*m;i++){
q[x][y]=i;
int a=x+dx[d],b=y+dy[d];//开始挪动
if(a<0||a>=n||b<0||b>=m||q[a][b]!=0)//判断神魔时候撞墙,一种是出借,另一种是到了原来填过的位置
{
d=(d+1)%4;
a=x+dx[d];
b=y+dy[d];
}
x=a;
y=b;
}
for(int[] res:q){
for(int val:res){
System.out.printf("%d ",val);
}
System.out.println();
}
}
}
c++代码实现
#include<iostream>
using namespace std;
const int N = 110;
int q[N][N];
int n, m;
int main()
{
cin >> n >> m;
int dx[] = { -1,0,1,0 }, dy[] = { 0,1,0,-1 };
int x = 0, y = 0, d = 1;
for (int i = 1; i <= n * m; i++)
{
q[x][y] = i;
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a >= n || b < 0 || b >= m || q[a][b]) {
d = (d + 1) % 4;
a = x + dx[d] , b = y + dy[d];
}
x = a , y = b;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << q[i][j] << " ";
}
cout << endl;
}
return 0;
}