這是我第一次打卡,目的就是但願本身一直保持學習的狀態,天天都瞭解一些新的技術;同時這也是我第一篇博客,寫得很差還請見諒!程序員
542.01 Matrix
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
Example 1:算法
Input: [[0,0,0], [0,1,0], [0,0,0]] Output: [[0,0,0], [0,1,0], [0,0,0]]
Example 2:數組
Input: [[0,0,0], [0,1,0], [1,1,1]] Output: [[0,0,0], [0,1,0], [1,2,1]]
解答:首先很容易就想到DP,dist[i,j]=min(dist[i-1,j]+1, disti+1+1, disti+1, disti+1, disti),每一個點與它的鄰接點對比,取最小的,掃描每一行每一列,直到沒有變動爲止,代碼以下:函數
class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>> &matrix) { vector<vector<int>> ret(matrix.size()); int max = 10001; for (int i = 0; i < matrix.size(); i++) { vector<int> vRow(matrix[i].size()); for (int j = 0; j < matrix[i].size(); j++) { vRow[j] = matrix[i][j] == 0 ? 0 : max; } ret[i] = vRow; } bool b = true; while (b) { b = false; for (int i = 0; i < matrix.size(); i++) { for (int j = 0; j < matrix[i].size(); j++) { //up if (i - 1 >= 0 && ret[i][j] > ret[i - 1][j] + 1) { b = true; ret[i][j] = ret[i - 1][j] + 1; } //down if (i + 1 < matrix.size() && ret[i][j] > ret[i + 1][j] + 1) { b = true; ret[i][j] = ret[i + 1][j] + 1; } //left if (j - 1 >= 0 && ret[i][j] > ret[i][j - 1] + 1) { b = true; ret[i][j] = ret[i][j - 1] + 1; } //right if (j + 1 < matrix[i].size() && ret[i][j] > ret[i][j + 1] + 1) { b = true; ret[i][j] = ret[i][j + 1] + 1; } } } } return ret; } };
這種算法的時間複雜度爲O(r*c*k),其中r和c分別爲行數和列數,k是迭代的次數,若是0和1都相距很近的話,這個算法很快就迭代完成,然而若是0和1相距很遠,好比矩陣只有左上角存在一個0,那麼右下角的1須要迭代約(r+c)/2次,這樣最糟的狀況時間複雜度會上升一個級別,代碼提交,耗時188ms;學習
因而想另一種算法減小冗餘的計算,很容易就想到每一個0點就像水裏的波浪同樣,一步一步的往四周擴散,每一次擴散(距離+1),獲得的結果就是最終結果,因而就聯想到BFS算法,代碼以下(耗時168ms):編碼
class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>> &matrix) { int row = matrix.size(); int col = matrix[0].size(); vector<vector<int>> ret(row, vector<int>(col, -1)); struct Point{ int x; int y; public: Point(int _x, int _y) { x = _x; y = _y; } Point() { x = 0; y = 0; } }; struct Point p[10001]; int l = 0, r = 0; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (matrix[i][j] == 0) { ret[i][j] = 0; p[r++] = Point(i, j); } } } Point diff[4] = {{-1,0}, {1,0}, {0,-1}, {0,1}}; while (l < r) { Point cur = p[l++]; int nextDist = ret[cur.x][cur.y] + 1; for (int i = 0; i < 4; i++) { int newX = cur.x + diff[i].x; int newY = cur.y + diff[i].y; if (newX >=0 && newX < row && newY >= 0 && newY < col && ret[newX][newY] == -1) { ret[newX][newY] = nextDist; p[r++] = Point(newX, newY); } } } return ret; } };
這裏有個點須要注意下,就是定義結構數組struct Point p[10001],一開始個人Point結構只定義帶參數的構造函數,而後這句p[10001]的定義編譯不過,網上查了下結構數組的定義,一大堆文章的解決方案都是定義數組的同時初始化數組,但我這裏顯然沒辦法初始化。後面想到既然沒有初始化數據,那是否須要定義一個默認的無參數構造函數,果真加上以後編譯經過了。rest
這周閱讀的文章是GameDev Protips: How To Survive As An Indie Developer,做者Daniel Doan提出,做爲一個遊戲獨立開發者,想要在遊戲行業中生存下來,須要學會如下幾點:code
最近開始用vscode(之前習慣用sublime),這裏分享幾個我以爲比較經常使用的快捷鍵和設置吧接口
分享一篇關於服務調用的文章
終於有人把服務調用說清楚了遊戲