我有这个矩阵:
1 2 3 4 5
6 7 8 9 A
B C D E F
0 1 2 3 4
我希望它打印在一行中,如下所示:
1 6 2 B 7 3 0 C 8 4 1 D 9 5 2 E A 3 F 4.
最简单的方法是如何做到这一点?
使用嵌套循环。外环距离 (0,0)
内循环 i 和 j 的所有有效组合,总和为距离。
#include <iostream>
int main(int argc, char **argv)
{
char m[4][5] = { { '1', '2', '3', '4', '5' },
{ '6', '7', '8', '9', 'A' },
{ 'B', 'C', 'D', 'E', 'F' },
{ '0', '1', '2', '3', '4' } };
for (int i = 0; i <= 3; ++i) {
for (int j = 0; j <= i; ++j) {
std::cout << m[i - j][j] << " ";
}
}
for (int i = 4; i <= 7; ++i) {
for (int j = i - 3; j <= 4; ++j) {
std::cout << m[i - j][j] << " ";
}
}
std::cout << std::endl;
return 0;
}
如果矩阵存储在这样的数组中:
#include <stdio.h>
int main(void) {
char matrix[4][5] = {{'1','2','3','4','5'},
{'6','7','8','9','A'},
{'B','C','D','E','F'},
{'0','1','2','3','4'}};
int cols = 5;
int rows = 4;
int i = 0;
for( i = 0; i < cols + rows -2 ; i++){
int j = 0;
while(j <= i){
int k = i-j;
if(k < rows && j < cols){
printf("%c ",matrix[k][j]);
}
j++;
}
}
}
对于总索引的每个值,我只是从 0 到行和列的总索引(在这种情况下从 0 到 7),打印值,列和行的总和等于当前总索引,如果索引可用(较小比列和行的索引),打印它,否则转义。例如:
0 - 00
1 - 10 01
2 - 20 11 02
顺便说一句,似乎需要比其他更多的循环
I would suggest a vector<vector<char> >
representation for the matrix(if I assume that you store chars in each cell). An important observation is that for each diagonal you have the sum of the i and j indices a constant and this sum increases by one for the diagonals.
Having noticed this you make an outer cycle over the sum and inner cycle over the x coordinate. Beware not to fall out of the matrix! Now the easiest c++ way to print the matrix would be:
vector<vector<char> > a;
for(unsigned sum = 0; sum < a.size() + a[0].size(); ++sum) {
for (unsigned j = 0; j <= sum && j < a[0].size(); ++j) {
unsigned i = sum - j;
if (i >= a.size()) {
continue;
}
cout << a[i][j] << " ";
}
}
One can optimize the cycle over j by changing the start value(so that the continue condition is never true) but the code would have been harder to understand. Another nit I did not fix on purpose is that an blank is printed even after the last element. This is yeat another check that needs to be added.
Hope this helps.
for( int i = 0; i < matrix.cx; i++ ) {
for( int j = 0; j < matrix.cy; j++ ) {
std::cout << matrix[i][j] << ' ';
}
// comment following line to make matrix printed in one line
std::cout << std::endl;
}