原文:
给定一个 2d 数组,以之字形打印它。 例:
input :
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
output :
1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 20 19 18 17 16
input :
10 24 32
50 6 17
99 10 11
output :
10 24 32 17 6 50 99 10 11
c
// c program to print
// matrix in zig-zag form
#include
using namespace std;
// method to print matrix in zig-zag form
void printzigzag(int row, int col, int a[][5])
{
int evenrow = 0; //starts from the first row
int oddrow = 1; //starts from the next row
while (evenrow=0; i--)
{
// oddrow will be printed in
// the opposite direction
cout<= 0; i--)
{
// oddrow will be printed in the opposite direction
system.out.print(a[oddrow][i] " ");
}
}
// skipping next row so as to get the next oddrow
oddrow = oddrow 2;
}
}
public static void main(string[] args)
{
int r = 3, c = 5;
int mat[][] = { {1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15}};
printzigzag(r , c , mat);
}
}
# python 3 program to print
# matrix in zig-zag form
# method to print matrix
# in zig-zag form
def printzigzag(row, col, a):
evenrow = 0 # starts from the first row
oddrow = 1 # starts from the next row
while evenrow < row:
for i in range(col):
# evenrow will be printed
# in the same direction
print(str(a[evenrow][i] ),
end = " ")
# skipping next row so as
# to get the next evenrow
evenrow = evenrow 2
if oddrow < row:
for i in range(col - 1, -1, -1):
# oddrow will be printed in
# the opposite direction
print(str(a[oddrow][i]),
end = " ")
# skipping next row so as
# to get the next oddrow
oddrow = oddrow 2
# driver code
r = 3
c = 5
mat = [[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]];
printzigzag(r , c , mat)
# this code is contributed
# by chitranayal
// c# program to print matrix in zig-zag form
using system;
public class gfg {
// method to print matrix in zig-zag form
static void printzigzag(int row, int col, int[, ] a)
{
// starts from the first row
int evenrow = 0;
// starts from the next row
int oddrow = 1;
while (evenrow < row) {
for (int i = 0; i < col; i ) {
// evenrow will be printed in
// the same direction
console.write(a[evenrow, i] " ");
}
// skipping next row so as to get the
// next evenrow
evenrow = evenrow 2;
if(oddrow < row)
{
for (int i = col - 1; i >= 0; i--)
{
// oddrow will be printed in the
// opposite direction
console.write(a[oddrow, i] " ");
}
}
// skipping next row so as to get
// the next oddrow
oddrow = oddrow 2;
}
}
public static void main()
{
int r = 3, c = 5;
int[, ] mat = { { 1, 2, 3, 4, 5 },
{ 6, 7, 8, 9, 10 },
{ 11, 12, 13, 14, 15 }
};
printzigzag(r, c, mat);
}
}
// this code is contributed by vt_m.
= 0; $i--)
{
// oddrow will be printed in
// the opposite direction
echo $a[$oddrow][$i], " ";
}
}
// skipping next row so as
// to get the next oddrow
$oddrow = $oddrow 2;
}
}
// driver code
$r = 3; $c = 5;
$mat = array(array(1, 2, 3, 4, 5),
array(6, 7, 8, 9, 10),
array(11, 12, 13, 14, 15));
printzigzag($r , $c , $mat);
// this code is contributed by m_kit.
?>
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处