题解 | #顺时针旋转矩阵 逐圈模拟#

顺时针旋转矩阵

http://www.nowcoder.com/practice/2e95333fbdd4451395066957e24909cc

import java.util.*;

public class Solution {
    public int[][] rotateMatrix(int[][] mat, int n) {
        // write code here
        if (n == 0){
            return new int[][]{};
        }
        int firstRow = 0;
        int firstCol = 0;
        int lastRow = n - 1;
        int lastCol = n - 1;
        while (firstRow < lastRow && firstCol < lastCol){
            process(mat, firstRow++, firstCol++, lastRow--, lastCol--);
        }
        return mat;
    }
    public static void process(int[][] mat, int fr, int fc, int lr, int lc){
        if (fr >= lr || fc >= lc){
            return;
        }
        int temp = 0;
        for (int i = 0; i < lc - fc; i++) {
            temp = mat[fr][fc + i];
            mat[fr][fc + i] = mat[lr - i][fc];
            mat[lr - i][fc] = mat[lr][lc - i];
            mat[lr][lc - i] = mat[fr + i][lc];
            mat[fr + i][lc] = temp;
        }
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务