题解 | #顺时针打印矩阵#

顺时针打印矩阵

https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a

import java.util.*;
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        int startRows = 0;
        int startCols = 0;
        int endRows = matrix.length - 1;
        int endCols = matrix[0].length - 1;
        ArrayList<Integer> list = new ArrayList<>();
        while (startRows <= endRows && startCols <= endCols) {
            if (startRows == endRows) {
                for (int i = startCols; i <= endCols; i++) {
                    list.add(matrix[startRows][i]);
                }
                break;
            }
            if (startCols == endCols) {
                for (int i = startRows; i <= endRows; i++) {
                    list.add(matrix[i][startCols]);
                }
                break;
            }
            for (int i = startCols; i <= endCols - 1; i++) {
                list.add(matrix[startRows][i]);
            }
            for (int i = startRows; i <= endRows - 1; i++) {
                list.add(matrix[i][endCols]);
            }
            for (int i = endCols; i >= startCols + 1; i--) {
                list.add(matrix[endRows][i]);
            }
            for (int i = endRows; i >= startRows + 1; i--) {
                list.add(matrix[i][startCols]);
            }
            startRows++;
            endRows--;
            startCols++;
            endCols--;
        }

        return list;
    }
}

全部评论

相关推荐

06-24 19:27
云南大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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