My OO inspired solution, easy to understand, 90% of the code can used for both Spiral Matrix problem


  • 0
    D
    public class Solution {
        int l = 0; //left
        int r;  //right
        int t = 0; //top
        int b;  //bottom
        int i = 0;
        int j = 0;
        int direction = 0; //0:east ; 1:south ; 2:west ; 3:north
    
        public int[][] generateMatrix(int n) {
            int[][] ret = new int[n][n];
            if (n == 0) return ret;
            r = n - 1;
            b = n - 1;
            int num = 1;
            while (l <= r && t <= b) {
                ret[i][j] = num;
                if (isBlocked()) {
                    removePast();
                    turnRight();
                }
                move();
                num++;
            }
            return ret;
        }
    
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> ret = new LinkedList<Integer>();
            if (matrix.length == 0) return ret;
            r = matrix[0].length - 1;
            b = matrix.length - 1;
            while (l <= r && t <= b) {
                ret.add(matrix[i][j]);
                if (isBlocked()) {
                    removePast();
                    turnRight();
                }
                move();
                
            }
            return ret;
        }
    
        private void removePast(){
            switch(direction) {
                case 0:
                    t++;
                    break;
                case 1:
                    r--;
                    break;
                case 2:
                    b--;
                    break;
                case 3:
                    l++;
                    break;
                default:
                    
            }
        }
        
        private boolean isBlocked(){
            switch(direction) {
                case 0:
                    return j == r;
                case 1:
                    return i == b;
                case 2:
                    return j == l;
                case 3:
                    return i == t;
                default:
                    return false;
            }
        }
    
        private void turnRight(){
            direction = (direction + 1) % 4;
        }
    
        private void move(){
            switch(direction) {
                case 0:
                    j++;
                    break;
                case 1:
                    i++;
                    break;
                case 2:
                    j--;
                    break;
                case 3:
                    i--;
                    break;
                default:
                    break;
            }
        }
    }

Log in to reply
 

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