classSolution{public:vector<vector<int>>spiralMatrix(intm,intn,ListNode*head){constexprintkDirs[4][2]={{0,1},{1,0},{0,-1},{-1,0}};vector<vector<int>>ans(m,vector<int>(n,-1));intx=0;// the current x positioninty=0;// the current y positionintd=0;for(ListNode*curr=head;curr;curr=curr->next){ans[x][y]=curr->val;if(x+kDirs[d][0]<0||x+kDirs[d][0]==m||y+kDirs[d][1]<0||y+kDirs[d][1]==n||ans[x+kDirs[d][0]][y+kDirs[d][1]]!=-1)d=(d+1)%4;x+=kDirs[d][0];y+=kDirs[d][1];}returnans;}};
1 2 3 4 5 6 7 8 9101112131415161718192021
classSolution{publicint[][]spiralMatrix(intm,intn,ListNodehead){finalint[][]DIRS={{0,1},{1,0},{0,-1},{-1,0}};int[][]ans=newint[m][n];Arrays.stream(ans).forEach(A->Arrays.fill(A,-1));intx=0;// the current x positioninty=0;// the current y positionintd=0;for(ListNodecurr=head;curr!=null;curr=curr.next){ans[x][y]=curr.val;if(x+DIRS[d][0]<0||x+DIRS[d][0]==m||y+DIRS[d][1]<0||//y+DIRS[d][1]==n||ans[x+DIRS[d][0]][y+DIRS[d][1]]!=-1)d=(d+1)%4;x+=DIRS[d][0];y+=DIRS[d][1];}returnans;}}
1 2 3 4 5 6 7 8 910111213141516171819
classSolution:defspiralMatrix(self,m:int,n:int,head:ListNode|None)->list[list[int]]:DIRS=((0,1),(1,0),(0,-1),(-1,0))ans=[[-1]*nfor_inrange(m)]x=0# the current x positiony=0# the current y positiond=0curr=headwhilecurr:ans[x][y]=curr.valif(x+DIRS[d][0]<0orx+DIRS[d][0]==mory+DIRS[d][1]<0ory+DIRS[d][1]==norans[x+DIRS[d][0]][y+DIRS[d][1]]!=-1):d=(d+1)%4x+=DIRS[d][0]y+=DIRS[d][1]curr=curr.nextreturnans
Thanks for stopping by! If you find this site helpful, consider buying me some protein powder to keep me fueled! π