文章

19

粉丝

0

获赞

125

访问

3.0k

头像
旋转方阵 题解:

#include <bits/stdc++.h>
using namespace std;

int main() {
	int n;
	cin >> n;  // 输入方阵的大小

	vector<vector<int>> matrix(n, vector<int>(n));  // 定义 n*n 的矩阵,n代表行数,vector<int>(n)代表列数
	int num = 1;  // 当前填充的数字
	int left = 0, right = n - 1, top = 0, bottom = n - 1;  // 定义边界

	while (left <= right && top <= bottom) {
		// 从上到下填充左边界
		for (int i = top; i <= bottom; i++) {
			matrix[i][left] = num++;
		}
		left++;

		// 从左到右填充下边界
		for (int i = left; i <= right; i++) {
			matrix[bottom][i] = num++;
		}
		bottom--;

		// 从下到上填充右边界
		for (int i = bottom; i >= top; i--) {
			matrix[i][right] = num++;
		}
		right--;

		// 从右到左填充上边界
		for (int i = right; i >= left; i--) {
			matrix[top][i] = num++;
		}
		top++;
	}

	// 输出矩阵
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			printf("%-4d", matrix[i][j]);  // 格式化输出,每个数字占4位
		}
		cout << endl;
	}

	return 0;
}
...
登录查看完整内容


登录后发布评论

3 条评论
tomatocate
2025年3月7日 22:46

问一下大佬是怎么知道输出占4位的? 

printf("%-4d", matrix[i][j]); // 格式化输出,每个数字占4位

赞(0)

jaygee_ : 回复 tomatocate: 选中输出,可以看到数据右端有三空格,一开始我是在输出后补三空格" ",PE了,发现最下层数字与上层数字对不齐所以选择了输出占4位

2025年3月8日 08:10

tomatocate : 回复 jaygee_: 好的好的,谢谢佬!

2025年3月8日 12:13