Rotate Image

Leave a comment

October 31, 2016 by oneOokay

普通的array操作。

“剥洋葱”法一层一层的旋转。注意旋转的坐标的对应改变以及offset的用法。

public class Solution {
public void rotate(int[][] matrix) {
int start = 0;  //行
int end = matrix.length – 1; //列
while (start < end){ //每一次while loop结束说明完成了一层旋转。
for (int i = start; i < end; i ++) { //逐个旋转
int offset = i – start;  //offset之后用来计算每个的位
int tmp = matrix[start][i]; //从横着的上行开始,暂存好这一点的值
matrix[start][i] = matrix[end – offset][start]; //旋转后,放在[start][i]的位置上的值为:竖左的值:竖左的行数为(想象横上是从左上角忘右平移,所以竖左的行为是从左下向上平移)所以坐标为:行数发生offset的变化,而列数不变,依旧为start。所以是:[end-offset][start]:
matrix[end – offset][start] = matrix[end][end – offset]; //接着横下的值将会成为竖左的值,横下是由右下角向左平移,行数不变,列发生变化。所以坐标为:[end][end – offset]
matrix[end][end – offset] = matrix[start + offset][end];//接着竖右的值会变成横下的值。竖右是由右上角向下平移,列数不变。所以坐标为[start + offset][end]
matrix[start + offset][end] = tmp;
}
start ++; //剥完一层洋葱了,继续剥下一层。
end –;
}}}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: