C++?LeetCode542矩陣示例詳解
LeetCode 542.01 矩陣
力扣題目鏈接:leetcode.cn/problems/01…
給定一個由 0
和 1
組成的矩陣 mat
,請輸出一個大小相同的矩陣,其中每一個格子是 mat
中對應(yīng)位置元素到最近的 0
的距離。
兩個相鄰元素間的距離為 1
。
示例 1:
輸入:mat = [[0,0,0],[0,1,0],[0,0,0]]
輸出:[[0,0,0],[0,1,0],[0,0,0]]
示例 2:
輸入:mat = [[0,0,0],[0,1,0],[1,1,1]]
輸出:[[0,0,0],[0,1,0],[1,2,1]]
提示:
m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
mat[i][j] is either 0 or 1.
mat
中至少有一個0
方法一:廣度優(yōu)先搜索
首先遍歷原始矩陣,找到所有的0,將其位置入隊。
接著在隊列不為空時,不斷出隊一個位置,并判斷這個位置的上下左右是否被遍歷過。
如果還沒有被遍歷過,那么就將新的位置入隊。并將地圖中新的位置的值修改為“出隊位置的值 + 1”
原理:
所有的原始的0最終結(jié)果都是0。廣度優(yōu)先搜索就是在所有的“0”的位置中,走一步。這一步所到的位置就是“1”步能到達的位置。同理,“1”經(jīng)過一步到達的位置就是“2”。最先到達的就是步數(shù)最少的。
- 時間復(fù)雜度O(nm)
- 空間復(fù)雜度O(nm)
AC代碼
C++
typedef pair<int, int> pii; const int direcitons[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>>& mat) { int n = mat.size(), m = mat[0].size(); vector<vector<bool>> visited(n, vector<bool>(m, false)); queue<pii> q; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (!mat[i][j]) { visited[i][j] = true; q.push({i, j}); } } } while (q.size()) { pii thisNode = q.front(); q.pop(); for (int d = 0; d < 4; d++) { int tx = thisNode.first + direcitons[d][0]; int ty = thisNode.second + direcitons[d][1]; if (tx >= 0 && tx < n && ty >= 0 && ty < m) { if (!visited[tx][ty]) { visited[tx][ty] = true; mat[tx][ty] = mat[thisNode.first][thisNode.second] + 1; q.push({tx, ty}); } } } } return mat; } };
以上就是C++ LeetCode542矩陣示例詳解的詳細內(nèi)容,更多關(guān)于C++ LeetCode542矩陣的資料請關(guān)注腳本之家其它相關(guān)文章!