#include <iostream> using namespace std; int main() { int n; cin >> n; int arr[100][100] = {0}; // 初始化矩阵 int row = 0, col = 0, num = 1; arr[row][col] = num++; // 初始值 while(num <= n * n) { // 向右上方填充数字 while(row > 0 && col < n - 1 && !arr[row - 1][col + 1]) { arr[--row][++col] = num++; } // 向左下方填充数字 while(row < n - 1 && col > 0 && !arr[row + 1][col - 1]) { arr[++row][--col] = num++; } // 如果不能向右上或左下填充,则向下填充数字 if(row < n - 1 && !arr[row + 1][col]) { arr[++row][col] = num++; } // 如果不能向下填充,则向右填充数字 else if(col < n - 1 && !arr[row][col + 1]) { arr[row][++col] = num++; } } // 输出矩阵 for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { cout << arr[i][j] << " "; } cout << endl; } return 0; }优化这段代码
时间: 2024-01-27 21:03:11 浏览: 41
好的,以下是对这段代码的优化:
1. 少定义变量,减少内存占用。可以将num变量合并到row和col变量中,用row * n + col + 1来表示当前填入的数字。
2. 不需要初始化矩阵,只需要在填数时判断当前位置是否为0即可。
3. 将判断是否能向右上或左下填数的条件合并为一个条件判断语句。
4. 将向下和向右填数的顺序颠倒,这样可以保证填数的顺序更加合理,最后的矩阵更加美观。
优化后的代码如下:
```c++
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int row = 0, col = 0;
while(row < n && col < n)
{
int num = row * n + col + 1;
if(row > 0 && col < n - 1 && !arr[row - 1][col + 1])
{
arr[--row][++col] = num;
}
else if(row < n - 1 && col > 0 && !arr[row + 1][col - 1])
{
arr[++row][--col] = num;
}
else if(row < n - 1 && !arr[row + 1][col])
{
arr[++row][col] = num;
}
else if(col < n - 1 && !arr[row][col + 1])
{
arr[row][++col] = num;
}
else
{
break;
}
}
// 输出矩阵
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
需要注意的是,优化后的代码仅仅是针对这段代码的优化,如果需要更加高效的实现方法,还需要根据具体的应用场景进行优化。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)