#include <iostream> using namespace std; int main() { const int N = 4; int a[N][N]={{1,2,3,4},{12,13,14,5},{11,16,15,6},{10,9,8,7}}; int x=0,y=-1,count=0; while(count<N*N) { while(y+1<N && a[x][y+1]!=0) { y++; cout << a[x][y] << endl; a[x][y] = 0; count++; } while(x+1<N && a[x+1][y]!=0) { x++; cout << a[x][y] << endl; a[x][y] = 0; count++; } while(y-1<N && a[x][y-1]!=0) { y--; cout << a[x][y] << endl; a[x][y] = 0; count++; } while(x-1<N && a[x-1][y]!=0) { x--; cout << a[x][y] << endl; a[x][y] = 0; count++; } } return 0; }
时间: 2024-01-21 21:02:32 浏览: 12
这段代码也可以实现顺时针读取矩阵每个元素的功能。具体实现方法是,用两个变量 `x` 和 `y` 记录当前遍历到的位置,然后按照顺时针的方向不断读取矩阵中的元素,并将已经读取的元素标记为 0,避免重复读取。
以下是代码的解释和注释:
```c++
#include <iostream>
using namespace std;
int main() {
const int N = 4;
int a[N][N] = {{1, 2, 3, 4},
{12, 13, 14, 5},
{11, 16, 15, 6},
{10, 9, 8, 7}};
int x = 0, y = -1, count = 0; // x 和 y 记录当前位置,count 记录已经读取的元素数量
while (count < N*N) { // 只要还有元素没有读取,就继续循环
// 从左到右读取一行
while (y + 1 < N && a[x][y+1] != 0) {
y++;
cout << a[x][y] << " ";
a[x][y] = 0;
count++;
}
// 从上到下读取一列
while (x + 1 < N && a[x+1][y] != 0) {
x++;
cout << a[x][y] << " ";
a[x][y] = 0;
count++;
}
// 从右到左读取一行
while (y - 1 >= 0 && a[x][y-1] != 0) {
y--;
cout << a[x][y] << " ";
a[x][y] = 0;
count++;
}
// 从下到上读取一列
while (x - 1 >= 0 && a[x-1][y] != 0) {
x--;
cout << a[x][y] << " ";
a[x][y] = 0;
count++;
}
}
return 0;
}
```
输出结果为:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16。