My 172ms accepted Java solution


  • 0
    J
    public class Solution {
    	public int[][] generateMatrix(int n) {
    		int result[][]=new int[n][n];
    		int topwall=-1,leftwall=-1,rightwall=n,bottomwall=n;
            int x=0,y=0,num=1;
            char direc='R';
            while(topwall<bottomwall-1&&leftwall<rightwall-1){
            	result[x][y]=num;
            	num++;
            	switch(direc){
            	case 'R':
            		if(y==rightwall-1){
            			direc='D';
            			topwall++;
            			x++;
            		}
            		else y++;
            		break;
            	case 'D':
            		if(x==bottomwall-1){
            			direc='L';
            			rightwall--;
            			y--;
            		}
            		else x++;
            		break;
            	case 'L':
            		if(y==leftwall+1){
            			direc='U';
            			bottomwall--;
            			x--;
            		}
            		else y--;
            		break;
            	case 'U':
            		if(x==topwall+1){
            			direc='R';
            			leftwall++;
            			y++;
            		}
            		else x--;
            	}	
            }
            return result;
    	  
    	}
    
    }

Log in to reply
 

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