Share my ac java solution


  • 0
    I
    public class Solution {
        public void anotherHelper(int[][] num, List<Integer> result, int x, int loopx, int y, int loopy) {
            if (x > (num.length / 2) && y >= (num[0].length / 2)) {
                return;
            }
            if (loopx <= 0 || loopy <= 0)
                return;
            for (int i = y; i < y + loopy; ++i) {
                result.add(num[x][i]);
            }
            for (int i = x + 1; i < x + loopx; ++i) {
                result.add(num[i][y+loopy-1]);
            }
            if (x != (x + loopx -1)) {
                for (int i = y + loopy - 2; i > y - 1; --i) {
                    result.add(num[x+loopx-1][i]);
                }
            }
            if (y != (y + loopy - 1)) {
                for (int i = x + loopx - 2; i > x; --i) {
                    result.add(num[i][y]);
                }
            }
            anotherHelper(num, result, x + 1, loopx - 2, y + 1, loopy - 2);
        }
    
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> result = new ArrayList<Integer>();
            if (matrix.length == 0) {
                return result;
            }
            anotherHelper(matrix, result, 0, matrix.length, 0, matrix[0].length);
            return result;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.