Java Clean Code


  • 0
    M

    I hava a simple and easy to understand solution.

    public List<Integer> spiralOrder(int[][] matrix) {
            // write your code here
            List<Integer> res = new ArrayList<>();
            if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
                return res;
            }
            int n = matrix.length;
            int m = matrix[0].length;
            boolean[][] visited = new boolean[n][m];
            int cnt = 1;
            int x = 0;
            int y = 0;
            res.add(matrix[x][y]);
            visited[x][y] = true;
            while (cnt < n * m) {
                while (cnt < n * m && valid(x, y + 1, visited)) {
                    y += 1;
                    visited[x][y] = true;
                    res.add(matrix[x][y]);
                    cnt++;
                }
                while (cnt < n * m && valid(x + 1, y, visited)) {
                    x += 1;
                    visited[x][y] = true;
                    res.add(matrix[x][y]);
                    cnt++;
                }
                while (cnt < n * m && valid(x, y - 1, visited)) {
                    y -= 1;
                    visited[x][y] = true;
                    res.add(matrix[x][y]);
                    cnt++;
                }
                while (cnt < n * m && valid(x - 1, y, visited)) {
                    x -= 1;
                    visited[x][y] = true;
                    res.add(matrix[x][y]);
                    cnt++;
                }
            }
            return res;
        }
        public boolean valid(int x, int y, boolean[][] visited) {
            if (x < 0 || x >= visited.length) {
                return false;
            }
            if (y < 0 || y >= visited[0].length) {
                return false;
            }
            return !visited[x][y];
        }
    

Log in to reply
 

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