For instance, give row = 4, col = 5, print matrix in zigzag order like: [1, 8, 9, 16, 17]
[2, 7, 10, 15, 18]
[3, 6, 11, 14, 19]
[4, 5, 12, 13, 20]
package GooglePhone; import java.util.Arrays; public class PrintMatrix { static void print(int rows, int cols) {
int limit = rows * cols;
int T = rows * 2; // cycle
for (int i=1; i<=rows; i++) {
int[] curRow = new int[cols];
int k = 0;
int index = 0;
while (k * T + i <= limit || k * T + T - i + 1 <= limit) {
if (k * T + i <= limit) curRow[index++] = k * T + i;
if (k * T + T - i + 1 <= limit) curRow[index++] = k * T + T - i + 1;
k++;
}
System.out.println(Arrays.toString(curRow));
} }
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
print(4, 5);
//print(3, 5);
} }