LeetCode:Rotate Image

You are given an n*n 2D matrix representing an image.

Rotate the image by 90 degrees(clockwise).

Follow up: Could you do this in-place?

解題思路:

暴力法:從外到內一圈一圈地轉,不過這個方法效率太低,比較慢。

分析法:首先沿着副對角線翻轉一次,然後沿着水平中線翻轉一次。


代碼如下:

void rotate(vetor<vector<int>>& matrix) {
	const int n = matrix.size();
	for (itn i=0; i<n; ++i) {
		for (int j=0; j<n-i; ++j) { //沿着副對角線反轉
			swap (matrix[i][j], matrix[n-1-j][n-1-i]);
		}
	}
	for (int i=0; i<n/2; ++i) { //沿着水平中線反轉
		for (int j=0; i<n; ++j) {
			swap (matrix[i][j], matrix[n-1-i][j]);
		}
	}
}

當然也可以先沿着水平中線翻轉一次,然後沿着主對角線再翻轉一次。

代碼如下:

void rotate(vetor<vector<int>>& matrix) {
	const int n = matrix.size();

	for (int i=0; i<n/2; ++i) { //沿着水平中線反轉
		for (int j=0; i<n; ++j) {
			swap (matrix[i][j], matrix[n-1-i][j]);
		}
	}

	for (itn i=0; i<n; ++i) {
		for (int j=i+1; j<n; ++j) { //沿着主對角線反轉
			swap (matrix[i][j], matrix[j][i]);
		}
	}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章