LeetCode 542. 01 矩阵(BFS DP)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 542. 01 矩阵(BFS DP)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 解題
- 2.1 BFS
- 2.2 DP動態(tài)規(guī)劃
1. 題目
給定一個由 0 和 1 組成的矩陣,找出每個元素到最近的 0 的距離。
兩個相鄰元素間的距離為 1 。
示例 1: 輸入: 0 0 0 0 1 0 0 0 0 輸出: 0 0 0 0 1 0 0 0 0示例 2: 輸入: 0 0 0 0 1 0 1 1 1 輸出: 0 0 0 0 1 0 1 2 1注意: 給定矩陣的元素個數(shù)不超過 10000。 給定矩陣中至少有一個元素是 0。 矩陣中的元素只在四個方向上相鄰: 上、下、左、右。來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/01-matrix
著作權歸領扣網(wǎng)絡所有。商業(yè)轉載請聯(lián)系官方授權,非商業(yè)轉載請注明出處。
2. 解題
2.1 BFS
直白想法,每個點開啟bfs找到0就停止搜索,返回距離,更新矩陣,但是超時
class Solution {int r,c;vector<vector<int>> dir = {{0,1},{0,-1},{1,0},{-1,0}};queue<pair<int,int>> q; public:vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {int i, j, dis;r = matrix.size(), c = matrix[0].size();for(i = 0; i < r; ++i){for(j = 0; j < c; ++j){if(matrix[i][j] != 0){vector<vector<bool>> visited(r,vector<bool> (c,false));matrix[i][j] = bfs(i,j,matrix,visited);}}}return matrix;}int bfs(int i, int j, vector<vector<int>> &matrix, vector<vector<bool>> &visited){while(!q.empty())q.pop();visited[i][j] = true;q.push({i,j});int xf,yf,x,y,n,k,distance = 0;while(!q.empty()){n = q.size();while(n--){xf = q.front().first;yf = q.front().second;q.pop();for(k = 0; k < 4; ++k){x = xf+dir[k][0];y = yf+dir[k][1];if((x>=0 && x<r)&&(y>=0 && y<c) && !visited[x][y]){if(matrix[x][y] != 0){q.push({x,y});visited[x][y] = true;}elsereturn distance+1;}}}++distance;}return distance;} };換個思路:
- 所有的為0的點先全部加入隊列
- 對隊列中所有的0點開啟BFS
- 訪問到了1,標記已訪問,更新矩陣值為距離
2.2 DP動態(tài)規(guī)劃
dist[i][j]dist[i][j]dist[i][j]表示該位置到0的最短距離
- 一個點1到0的最短距離可以從他的4個鄰居中+1得到(取最小的)
- 所有0點的最短距離distdistdist直接置為0
遍歷2次
- 先從左–》右,從上–》下
dist[i][j]=min(dist[i][j],dist[i?1][j]+1)dist[i][j] = min(dist[i][j], dist[i-1][j]+1)dist[i][j]=min(dist[i][j],dist[i?1][j]+1),上面的鄰居+1
dist[i][j]=min(dist[i][j],dist[i][j?1]+1)dist[i][j] = min(dist[i][j], dist[i][j-1]+1)dist[i][j]=min(dist[i][j],dist[i][j?1]+1),左邊的鄰居+1 - 再從從左《–右,從上《–下
dist[i][j]=min(dist[i][j],dist[i+1][j]+1)dist[i][j] = min(dist[i][j], dist[i+1][j]+1)dist[i][j]=min(dist[i][j],dist[i+1][j]+1),下面的鄰居+1
dist[i][j]=min(dist[i][j],dist[i][j+1]+1)dist[i][j] = min(dist[i][j], dist[i][j+1]+1)dist[i][j]=min(dist[i][j],dist[i][j+1]+1),右邊的鄰居+1
總結
以上是生活随笔為你收集整理的LeetCode 542. 01 矩阵(BFS DP)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 程序员面试金典 - 面试题 04.05.
- 下一篇: LeetCode 1333. 餐厅过滤器