首页 > 代码库 > Snapchat - 向左下角打印2D矩阵

Snapchat - 向左下角打印2D矩阵

题目是这样的,给一个2d矩阵,向左下角打印矩阵,比如

1,2,3,4

5,6,7,8

9,10,11,12

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

所以解题的重点是,结果里面的每一组,它们的横坐标+纵坐标是相等的,然后最大的可能是col+row-2

 1 public List<List<Integer>> printMatrix(int[][] board) {
 2         int height = board.length;
 3         int width = board[0].length;
 4         List<List<Integer>> res = new ArrayList<>();
 5         if (width == 0 || height == 0) {
 6             return res;
 7         }
 8         int diagonal = width + height - 2;
 9         for (int sum = 0; sum <= diagonal; sum++) {
10             List<Integer> cur = new ArrayList<>();
11             for (int y = 0; y <= sum; y++) {
12                 int x = sum - y;
13                 if (y < height && x < width) {
14                     //cur.add(y * width + x + 1);
15                     cur.add(board[y][x]);
16                 }
17             }
18             res.add(cur);
19         }
20         return res;
21     }

 

Snapchat - 向左下角打印2D矩阵