My brute force solution! Using direction


  • 0
    B
    public int[][] generateMatrix(int n) {
            int[][] res = new int[n][n];
            int lowBound = 0, highBound = n-1;
            int i=0, j=0, nCounter=0;
            char d = 'r';
            while (nCounter<n*n) {
                res[i][j] = ++nCounter;
                switch(d) {
                    case 'r': 
                        if (j==highBound) {
                            i++;
                            d = 'd';
                        }
                        else j++;
                        break;
                    case 'd':
                        if (i==highBound) {
                            j--;
                            d = 'l';
                        }
                        else i++;
                        break;
                    case 'l':
                        if (j==lowBound) {
                            i--;
                            d = 'u';
                            lowBound++;
                        }
                        else j--;
                        break;
                    case 'u':
                        if (i==lowBound) {
                            j++;
                            d = 'r';
                            highBound--;
                        }
                        else i--;
                        break;
                }
            }
            return res;
        }
    

Log in to reply
 

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