Concise Java Solution (good look code)


  • 0
    S

    Key point is current row/column 's fill in length get minus by one every two steps.

    I comment what each parameter represents. Easy to understand and good looking.

    public class Solution {
        public int[][] generateMatrix(int n) {
            int[][] m = new int[n][n];
            int len = n; // current row/column 's fill in length
            int index = 0; // direction controller
            int number = 1; // increasing numbers
            int x = 0, y = -1; // current position
            // fill in the matrix
            while(len > 0){
                if(index%2==1) len--;
                switch(index++%4){
                    case 0:
                        for(int i = 0;i < len;i++) m[x][++y] = number++;
                        break;
                    case 1:
                        for(int i = 0;i < len;i++) m[++x][y] = number++;
                        break;
                    case 2:
                        for(int i = 0;i < len;i++) m[x][--y] = number++;
                        break;
                    case 3:
                        for(int i = 0;i < len;i++) m[--x][y] = number++;
                        break;
                    default:
                    break;
                }
            }
            return m;
        }
    }

Log in to reply
 

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