Snap 面经题目:print diagonal

0002505492

题目:
给一个 int 矩阵,从左上角到右下角斜对角打印出来所有数字。

输入:
1 2 3 4
5 6 7 8
9 10 11 12
输出:
1
2 5
3 6 9
4 7 10
8 11
12

代码:


public class Solution {
	public static void print(int[][] matrix)
	{
		if(matrix == null || matrix[0].length == 0) return;
		int m = matrix.length, n = matrix[0].length;
		for(int j = 0; j < n; j++)
		{
			print(matrix, 0, j);
			System.out.println("");
		}
		for(int i = 1; i < m; i++)
		{
			print(matrix, i, n - 1);
			System.out.println("");
		}
	}
	private static void print(int[][] matrix, int i, int j)
	{
		int m = matrix.length;
		while(i < m && j >=0)
		{
			System.out.print(matrix[i][j] + " ");
			i++;
			j--;
		}
	}
	public static void main(String[] args)
	{
		int[][] input = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
		print(input);
	}
}

Output:

1 
2 5 
3 6 9 
4 7 10 
8 11 
12 

460total visits,1visits today