[The sword refers to the offer to brush the question] 40. Print the matrix clockwise

ideas

It is to simulate the problem of finding the law: according to the rules of the lower right and upper left

topic

Enter a matrix and print each number in clockwise order from the outside to the inside.
Sample

Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]

Output: [1,2,3,4,8,12,11,10,9,5,6,7]

java code

class Solution {
    
    
    public int[] printMatrix(int[][] matrix) {
    
    
        int res[] = {
    
    };
        int n = matrix.length;
        if (n == 0) return res;
        int m = matrix[0].length;
        Boolean st[][] = new Boolean[n][m];
        
        for (int i = 0; i < n; i++) {
    
    
            for (int j = 0; j < m; j++) {
    
    
                st[i][j] = false;
            }
        }
        
        res = new int[n * m];
        
        int dx[] = {
    
    0, 1, 0, -1}, dy[] = {
    
    1, 0, -1, 0};
        int x = 0, y = 0, d = 0; 
        for (int i = 0; i < n * m; i++) {
    
    
            res[i] = matrix[x][y];
            st[x][y] = true;
            int a = x + dx[d], b = y + dy[d];
            
            if (a < 0 || a >= n || b < 0 || b >= m || st[a][b]) {
    
    
                d = (d + 1) % 4;
                a = x + dx[d];
                b = y + dy[d];
            }
            
            x = a;
            y = b;
        }
        
        return res;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326125533&siteId=291194637