编程题#2: 二维数组右上左下遍历
来源: POJ (Coursera声明:在POJ上完成的习题将不会计入Coursera的最后成绩。)
注意: 总时间限制: 1000ms 内存限制: 65536kB
描述
给定一个row行col列的整数数组array,要求从array[0][0]元素开始,按从左上到右下的对角线顺序遍历整个数组。
输入
输入的第一行上有两个整数,依次为row和col。
余下有row行,每行包含col个整数,构成一个二维整数数组。
(注:输入的row和col保证0 < row < 100, 0 < col < 100)
输出
按遍历顺序输出每个整数。每个整数占一行。
样例输入
样例输出
参考代码1:
#include <iostream>
//#include <vector>
using namespace std;
int main()
{
int row = 0, rol = 0;
cin >> row >> rol;
// vector<vector<int>> array(row, rol);//使用vector提交作业提示:Compile Error,难道使用方法有误?本地运行时正确的
int array[100][100] = {0};
for (int i = 0; i < row; i++)
{
for (int j = 0; j < rol; j++)
{
cin >> array[i][j];
}
}
int x = 0, y = 0;
for (int i = 0; i < row+rol-1; i++)
{
x = i > rol-1? i-rol+1 : 0;
y = i-x;
while (x <= row-1 && y >= 0)
{
cout << array[x][y] << endl;
x++;
y--;
}
}
return 0;
}
参考代码2:
#include<iostream>
using namespace std;
int main() {
int row, col;
cin >> row >> col;
int shuzu[100][100];
for (int j = 0; j < row; j++) {
for (int o = 0; o < col; o++) {
cin >> shuzu[j][o];
}
}
int k = col + row - 1;//共有(行数+列数-1)条对角线
for (int i = 0; i <= k; ++i) {//对每一条对角线进行处理
int c = i - 1;//对角线行数列数起始点为0,每次+1;所以,刚好起始点横坐标是对角线编号-1
for (int r = 0; r < row; r++) {//同理
if (r>=0&&r < row&&c < col&&c>=0) {//通过这个,找到在范围内的。
cout << *(*(shuzu + r) + c) << endl;//只打印在范围内的
}
c--;//因为是由右边到左边,所以C--
}
}
return 0;
}