|
| 1 | +package offer; |
| 2 | + |
| 3 | +/** |
| 4 | + * @author : CodeWater |
| 5 | + * @create :2022-07-17-23:43 |
| 6 | + * @Function Description :29.顺时针打印矩阵 |
| 7 | + */ |
| 8 | +public class _29PrintMatrixClockwise { |
| 9 | + //==========================覆盖原数组的============================ |
| 10 | + class Solution { |
| 11 | + public int[] spiralOrder(int[][] matrix) { |
| 12 | + if( matrix.length == 0 ) return new int[0]; |
| 13 | + int n = matrix.length , m = matrix[0].length; |
| 14 | + int[] res = new int[ n * m ]; |
| 15 | + int x = 0 , y = 0 , d = 0 ; |
| 16 | + int[] dy = {1 , 0 , -1 , 0} , dx = {0 , 1 , 0 , -1}; |
| 17 | + for( int i = 0 ; i < n * m ; i++ ){ |
| 18 | + res[i] = matrix[x][y]; |
| 19 | + matrix[x][y] = Integer.MAX_VALUE; |
| 20 | + int a = x + dx[d] , b = y + dy[d]; |
| 21 | + if( a < 0 || a >= n || b < 0 || b >= m || matrix[a][b] == Integer.MAX_VALUE ){ |
| 22 | + d = (d + 1) % 4; |
| 23 | + a = x + dx[d]; |
| 24 | + b = y + dy[d]; |
| 25 | + } |
| 26 | + x = a ; |
| 27 | + y = b; |
| 28 | + } |
| 29 | + return res; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + //==========================开一个标志数组的============================ |
| 34 | + class Solution2 { |
| 35 | + public int[] spiralOrder(int[][] matrix) { |
| 36 | + if( matrix.length == 0 ) return new int[0]; |
| 37 | + int x = 0 , y = 0 , d = 1; |
| 38 | + int[] dx = {-1 , 0 , 1 , 0}; |
| 39 | + int[] dy = {0 , 1 , 0 , -1}; |
| 40 | + |
| 41 | + int n = matrix.length ;int m = matrix[0].length; |
| 42 | + int[] ans = new int[n * m]; |
| 43 | + |
| 44 | + boolean[][] flag = new boolean[n][m]; |
| 45 | + for( int i = 0 ; i < n * m ; i++ ){ |
| 46 | + flag[x][y] = true; |
| 47 | + ans[i] = matrix[x][y]; |
| 48 | + int a = x + dx[d] , b = y + dy[d]; |
| 49 | + if( a < 0 || a >= n || b < 0 || b >= m || flag[a][b] == true ){ |
| 50 | + d = (d + 1) % 4; |
| 51 | + a = x + dx[d] ; b = y + dy[d]; |
| 52 | + } |
| 53 | + x = a ; y = b; |
| 54 | + } |
| 55 | + return ans; |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments