Re: [閒聊] 每日LeetCode已回收

看板Marginalman作者 (みけねこ的鼻屎)時間2年前 (2023/05/10 17:42), 編輯推噓1(100)
留言1則, 1人參與, 2年前最新討論串317/719 (看更多)
59. Spiral Matrix II 給定一個數字 n ,返回大小為 n * n 的數字以漩渦方向排列的矩陣。 Example 1: https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg
Input: n = 3 Output: [[1,2,3],[8,9,4],[7,6,5]] 思路: 1.用dfs填充數字,填數字的方向為 往右->往下->往左->往上->往右->.... 遇到邊界或是格子不是0,就換方向填充。 Java Code: -------------------------------------------- class Solution { public int[][] generateMatrix(int n) { int[][] res = new int[n][n]; int[][] dict = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; res[0][0] = 1; int x = 0,y = 0,num = 2, dir = 0; while (num <= n*n){ int newX = x + dict[dir][0]; int newY = y + dict[dir][1]; if (newX >= 0 && newX < n && newY >= 0 && newY < n) { if (res[newY][newX] != 0){ dir = (dir + 1) % 4; } else { res[newY][newX] = num; x = newX; y = newY; num++; } } else { dir = (dir + 1) % 4; } } return res; } } -------------------------------------------- -- https://i.imgur.com/bFRiqA3.jpg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.75.86 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1683711775.A.D81.html

05/10 17:48, 2年前 , 1F
大師
05/10 17:48, 1F
文章代碼(AID): #1aMsSVs1 (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1aMsSVs1 (Marginalman)