按对角线顺序生成矩阵

按对角线顺序生成矩阵


旷视面试题
给定矩阵的行列,按对角线生成矩阵

	//例如行列分别为3,4
    //按对角线顺序(方向一致)
    //1 3 6
    //2 5 9
    //4 8 11
    //7 10 12

    public static int[][] generateMatrix(int m, int n){
        int[][] res = new int[m][n];
        int curVal = 1;
        for(int i = 1; i < m + n; i++){
            int row = 0, col = 0;
            if(i <= m){
                row = i - 1;
                col = 0;
            }else{
                row = m - 1;
                col = i - m;
            }
            res[row][col] = curVal++;
            while(true){
                if(--row >= 0 && ++col <= n - 1){
                    res[row][col] = curVal++;
                }else{
                    break;
                }
            }
        }
        return res;
    }
	//例如行列分别为3,4
    //按对角线顺序(之字形)
    //1 2 6
    //3 5 7
    //4 8 11
    //9 10 12

	public static int[][] generateMatrix(int m, int n){
		int[][] res = new int[m][n];
		int curVal = 1;
		int row = 0, col = 0;
		for(int i = 0; i < m * n; i++){
			res[row][col] = curVal++;
			if((row + col) % 2 == 0){
				if(col == n - 1){
					++row;
				}else if(row == 0){
					++col;
				}else{
					--row;
					++col;
				}
			}else{
				if(row == m - 1){
					++col;
				}else if(col == 0){
					++row;
				}else{
					++row;
					--col;
				}
			}
		}
		return res;
	}

你可能感兴趣的:(数据结构与算法,面试,算法,线性代数)