Amazon OA2准备——矩阵旋转

来源:互联网 发布:王珊 数据库 编辑:程序博客网 时间:2024/04/27 16:34

题目是给一个矩阵,再给一个flag,顺时针或者逆时针旋转矩阵。

在leetcode中有一道类似的题目,rotate image。不过leetcode的题目中的矩阵是正方形,也给定了是顺时针旋转的。

理清楚思维其实这道题就想出来了。


 01201231567

例如这么一个矩阵,变为

 01037126215

或者
 01051162273

这么的一个过程。

用长宽创建一个新的矩阵,对应数字放进去就可以了。我的程序中假定用户非常的友好,给的flag除了0,1不会输入其他的。这个也不是问题就是了。

private static int[][] rotate(int[][] matrix, int flag) {// TODO Auto-generated method stubif(matrix==null)return matrix;if(matrix.length < 2 && matrix[0].length < 2 )return matrix;int width = matrix[0].length;int height = matrix.length;int[][] newM = new int[width][height];if(flag == 1){newM = clockwise(matrix);}else{newM = counterclockwise(matrix);}return newM;}private static int[][] counterclockwise(int[][] matrix) {int width = matrix[0].length;int height = matrix.length;int[][] newM = new int[width][height];int h = 0;int w = width-1;for(int i=0; i < height; i++){for(int j=0; j < width; j++){newM[j][i] = matrix[h][w];w --;}if(w < 0)w = width-1;h ++;if(h > height)h = 0;}return newM;}private static int[][] clockwise(int[][] matrix) {// TODO Auto-generated method stubint width = matrix[0].length;int height = matrix.length;int[][] newM = new int[width][height];int h = height;int w = 0;for(int i=0; i < height; i++){for(int j=0; j < width; j++){newM[j][i] = matrix[h-1][w];w += 1;}if(w >= width)w = 0;h --;if(h < 0)h = height-1;}return newM;}


0 0
原创粉丝点击