劍指offer-js 順時針打印矩陣

順時針打印矩陣

題目描述:

輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字,
例如,如果輸入如下4 X 4矩陣: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 
則依次打印出數字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

問題分析:

定義四個變量,表示左上和右下的打印範圍,按照 右--下--左--上 一次旋轉打印結束後,
往對角分別前進和後退一個單位,也就是四個變量的值進行更改,直到最後循環結束

代碼展示:

function printMatrix(matrix)
{
    // write code here
    //input 
    // 1  2   3   4
    // 5  6   7   8
    // 9  10  11  12
    // 13 14  15  16
    
    //output
    // 1  2  3  4
    // 8 12 16 15
    // 14 13 9  5
    // 6  7  11 10
    var rows = matrix.length;	//行數 4
	var cols = matrix[0].length;	//列數 4
	var result = [];
	
	if(rows==0 && cols==0) 
		return result;
	var left = 0;	//0 3 0 3
	var right = cols-1;
	var top = 0;
	var bottom = rows-1;
	
	
	while(left<=right && top<=bottom){
		for(let i=left;i<=right;i++){
			result.push(matrix[top][i]);//1 2 3 4
		}
		for(let i=top+1;i<=bottom;i++){
			result.push(matrix[i][right]);//8 12 16
		}
		
		if(top != bottom){
			for(let i=right-1;i>=left;i--)
				result.push(matrix[bottom][i]);//15 14 13
		}
		if(left != right){
			for(let i=bottom-1;i>=top+1;i--){
				result.push(matrix[i][left]);//9 5
			}
		}
		left += 1;
		right -= 1;
		top += 1;
		bottom -= 1;
	}
	return result;
}

總結:

矩陣這裏,考察的是對於循環臨界值的判斷,在符合條件的情況下進行值的打印
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章