顺时针打印矩阵(数组)

来源:互联网 发布:ssd主控测试软件 编辑:程序博客网 时间:2024/05/21 09:10

题目描述:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

思路一:设计一个函数,递归调用

import java.util.ArrayList;public class Solution {    public ArrayList<Integer> printMatrix(int [][] matrix) {        if (matrix == null || matrix.length == 0) return null;        ArrayList<Integer> res = new ArrayList<>();        myPrint(matrix, 0, 0, matrix.length - 1, matrix[0].length - 1, res);        return res;    }    public void myPrint(int[][] matrix, int startRow, int startCol, int endRow, int endCol, ArrayList<Integer> result)    {        if (startRow < endRow && startCol < endCol)        {            for (int j = startCol; j <= endCol; j++) result.add(matrix[startRow][j]);            for (int i = startRow + 1; i <= endRow; i++) result.add(matrix[i][endCol]);            for (int j = endCol - 1; j >= startCol; j--) result.add(matrix[endRow][j]);            for (int i = endRow - 1; i >= startRow + 1; i--) result.add(matrix[i][startCol]);            myPrint(matrix, startRow + 1, startCol + 1, endRow - 1, endCol - 1, result);        }        else if (startRow == endRow && startCol < endCol)            for (int j = startCol; j <= endCol; j++) result.add(matrix[startRow][j]);        else if (startRow < endRow && startCol == endCol)            for (int i = startRow; i <= endRow; i++) result.add(matrix[i][startCol]);        else if (startRow == endRow && startCol == endCol)            result.add(matrix[startRow][startCol]);    }}


思路二:

m行,n列,循环的圈数为(Math.min(m, n) - 1) / 2 + 1;

第i圈中:

从左到右:行: i ;                                     列:i 到 n - 1 - i ;      列++

从上到下:行: i + 1 到 m - 1 - i ;           列:n - 1 - i;              行++

从右到左:行: m - 1 - i;                          列:n - 1 - i - 1 到 i; 列--

从下到上:行: m - 1 - i - 1 到 i + 1;       列:i;                         行-- 

import java.util.ArrayList;public class Solution {    public ArrayList<Integer> printMatrix(int [][] matrix) {        if (matrix == null || matrix.length == 0) return null;        ArrayList<Integer> res = new ArrayList<>();        int m = matrix.length;        int n = matrix[0].length;        int circles = (Math.min(m,n) - 1) / 2 + 1; // 圈数        for (int i = 0; i < circles; i++)        {            for (int c = i; c <= n - 1 - i; c++) res.add(matrix[i][c]);            for (int r = i + 1; r <= m - 1 - i; r++) res.add(matrix[r][n - 1 - i]);            for (int c = n - 1 - i - 1; (c >= i) && (m -1 - i != i); c--) res.add(matrix[m - 1 - i][c]);            for (int r = m - 1 - i - 1; (r >= i + 1) && (n - 1 - i != i); r--) res.add(matrix[r][i]);        }        return res;    }}



原创粉丝点击