Re: [閒聊] 每日leetcode

作者: enmeitiryous (enmeitiryous)   2024-09-09 08:33:11
題目: 2326. Spiral matrix IV
給你一個Link list,指定整數m,n請將Link list中的值從0,0的位置開始順時針螺旋的
填入m*n的2D vector中,不足者全填-1
思路:
照做,可以先用兩組vector紀錄x,y的移動慣例方向,當填完數字後看更新後的x,y loc
有沒有超出0-n-1, 0-m-1的範圍或是碰到ans[y][x]!=-1的格子,如果有的話則復原重新
換方向更新,beat70%以上有蠻多新做法來完成這個動作,可以多參考
vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) {
vector<vector<int>> ans(m,vector<int>(n,-1));
int nx=0;
int ny=0;
vector<int> dirx={1,0,-1,0};
vector<int> diry={0,1,0,-1};
int topc=0;
while(head){
ans[ny][nx]=head->val;
head=head->next;
nx+=dirx[topc%4];
ny+=diry[topc%4];
if(nx<0 || nx>n-1 || ny<0 || ny>m-1 || ans[ny][nx]!=-1){
nx-=dirx[topc%4];
ny-=diry[topc%4];
++topc;
nx+=dirx[topc%4];
ny+=diry[topc%4];
}
}
return ans;
}

Links booklink

Contact Us: admin [ a t ] ucptt.com