LeetCode 542. 01 矩阵(BFS DP)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 542. 01 矩阵(BFS DP)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 1. 題目
- 2. 解題
- 2.1 BFS
- 2.2 DP動(dòng)態(tài)規(guī)劃
1. 題目
給定一個(gè)由 0 和 1 組成的矩陣,找出每個(gè)元素到最近的 0 的距離。
兩個(gè)相鄰元素間的距離為 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注意: 給定矩陣的元素個(gè)數(shù)不超過 10000。 給定矩陣中至少有一個(gè)元素是 0。 矩陣中的元素只在四個(gè)方向上相鄰: 上、下、左、右。來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/01-matrix
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
2. 解題
2.1 BFS
直白想法,每個(gè)點(diǎn)開啟bfs找到0就停止搜索,返回距離,更新矩陣,但是超時(shí)
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;} };換個(gè)思路:
- 所有的為0的點(diǎn)先全部加入隊(duì)列
- 對(duì)隊(duì)列中所有的0點(diǎn)開啟BFS
- 訪問到了1,標(biāo)記已訪問,更新矩陣值為距離
2.2 DP動(dòng)態(tài)規(guī)劃
dist[i][j]dist[i][j]dist[i][j]表示該位置到0的最短距離
- 一個(gè)點(diǎn)1到0的最短距離可以從他的4個(gè)鄰居中+1得到(取最小的)
- 所有0點(diǎn)的最短距離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
總結(jié)
以上是生活随笔為你收集整理的LeetCode 542. 01 矩阵(BFS DP)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 程序员面试金典 - 面试题 04.05.
- 下一篇: LeetCode 1333. 餐厅过滤器