Title description
Input two integers n and m, output a matrix with n rows and m columns, and fill the matrix with numbers 1 to n*m in a serpentine shape.
The specific matrix form can refer to the sample.
Input format
Enter a line, containing two integers n and m.
Output format
Output the matrix that meets the requirements.
The matrix occupies n rows, and each row contains m integers separated by spaces.
data range
1≤n,m≤1001≤n,m≤100
Input sample:
3 3
Sample output:
1 2 3
8 9 4
7 6 5
Assign values to the places that have not been walked according to the direction of travel (bottom right and top left)
#include <iostream>
#include <cstdio>
using namespace std;
const int MAX = 109;
int a[MAX][MAX];
int main()
{
int n, m;
scanf("%d%d", &n, &m);
int sum = n * m;
int cnt = 0;
int row = 0;
int col = 0;
while(cnt < sum)
{
for(int i = 0; i < m; i++) // 右走
{
if(!a[row][i])
{
a[row][i] = ++ cnt;
col = i;
}
}
for(int i = row + 1; i < n; i++) // 下走
{
if(!a[i][col])
{
a[i][col] = ++cnt;
row = i;
}
}
for(int i = col - 1; i >= 0; i--) // 左走
{
if(!a[row][i])
{
a[row][i] = ++cnt;
col = i;
}
}
for(int i = row - 1; i >= 0; i--)
{
if(!a[i][col])
{
a[i][col] = ++cnt;
row = i;
}
}
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
printf("%d ", a[i][j]);
printf("\n");
}
return 0;
}