其他分享
首页 > 其他分享> > 蛇形填数的三种方法

蛇形填数的三种方法

作者:互联网

#include <iostream>
using namespace std;
int a[20][20];

int main() {
	int n, m;
	cin >> n >> m;
	int s = 1, z = 1, x = n, y = m, k = 1;
	while (s <= x && z <= y) {
		for (int i = s; i <= y; i++) {
			a[s][i] = k++;
		}
		for (int i = s + 1; i <= x; i++) {
			a[i][y] = k++;
		}
		for (int i = y - 1; i >= z; i--) {
			a[x][i] = k++;
		}
		for (int i = x - 1; i > s; i--) {
			a[i][z] = k++;
		}
		s++, z++, x--, y--;
	}
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cout << a[i][j] << " ";
		}
		cout << endl;
	}
}
#include <iostream>
using namespace std;
int a[20][20];

int main() {
	int n, m;
	cin >> n >> m;
	int s = 1, z = 1, x = n, y = m, k = 1;
	while (s <= x && z <= y) {
		for (int i = s; i <= y; i++) {
			a[s][i] = k++;
		}
		for (int i = s + 1; i <= x; i++) {
			a[i][y] = k++;
		}
		for (int i = y - 1; i >= z; i--) {
			a[x][i] = k++;
		}
		for (int i = x - 1; i > s; i--) {
			a[i][z] = k++;
		}
		s++, z++, x--, y--;
	}
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cout << a[i][j] << " ";
		}
		cout << endl;
	}
}
#include <iostream>
using namespace std;
int a[20][20];

int main() {
	int n, m;
	cin >> n >> m;
	int k = 1, z = 0, s = 0;
	int sum = n + m - 1;
	int x = n, y = m;
	for (int i = 0; i < x; i++) {
		int h = i;
		for (int j = 0; j <= i; j++) {
			if (h >= 0)
				a[h--][j] = k++;
			else
				break;
		}
	}
	for (int j = 1; j < y; j++) {
		int h = j;
		for (int i = x - 1; i >= 0; i--) {
			if (h < y)
				a[i][h++] = k++;
			else
				break;
		}
	}
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			cout << a[i][j] << " ";
		}
		cout << endl;
	}
	return 0;
}

标签:std,20,int,++,填数,三种,蛇形,--,main
来源: https://blog.csdn.net/m0_53709094/article/details/121932541