199. Judge Connection
Given a matrix of integers arr and an integer k, determine if all instances of value k in arr are connected. Two cells in a matrix are considered "connected" if they are horizontally or vertically adjacent and have the same value.
Example
Example 1:
Input:arr=[
[2,2,2,0],
[0,0,0,2],
[0,1,0,2],
[1,1,1,2]]
k=2
Output:false
Explanation: Not all `2` are connected to each other
Example 2:
Input:arr=[
[2,2,2,0],
[0,0,0,2],
[0,1,0,2],
[1,1,1,2]]
k=1
Output:true
Notice
∣arr∣≤500
∣arr[i]∣≤500
0≤arr[i][j]≤10000
[[2,2,2,0],[0,0,0,2],[0,1,0,2],[1,1,1,2]]
2
解法1:典型BFS
注意虽然只看1的链接,还是需要visited数组,不然多个1彼此死循环。
class Solution {
public:
/**
* @param arr: the arr
* @param k: the k
* @return: if all instances of value k in arr are connected
*/
bool judgeConnection(vector<vector<int>> &arr, int k) {
int nRow = arr.size();
if (nRow == 0) return false;
int nCol = arr[0].size();
if (nCol == 0) return false;
vector<vector<bool>> visited(nRow, vector<bool>(nCol, false));
int numK = 0;
int startX = 0, startY = 0;
for (int i = 0; i < nRow; ++i) {
for (int j = 0; j < nCol; ++j) {
if (arr[i][j] == k) {
numK++;
startX = i; startY = j;
}
}
}
visited[startX][startY] = true;
if (numK == 0) return false;
vector<int> dx = {0, 0, 1, -1};
vector<int> dy = {1, -1, 0, 0};
int countK = 0;
queue<pair<int, int>> q;
q.push({startX, startY});
countK = 1;
while(!q.empty()) {
auto curNode = q.front();
q.pop();
for (int i = 0; i < 4; ++i) {
int newX = curNode.first + dx[i];
int newY = curNode.second + dy[i];
if (newX < 0 || newX >= nRow || newY < 0 || newY >= nCol || visited[newX][newY] || arr[newX][newY] != k) continue;
visited[newX][newY] = true;
countK++;
q.push({newX, newY});
}
}
if (countK == numK) return true;
return false;
}
};
本文探讨了一个算法问题,即如何判断二维矩阵中所有相同特定值的元素是否相互连接。通过使用广度优先搜索(BFS)算法,我们能够有效地检查所有指定值的元素是否形成一个连续的区域。

被折叠的 条评论
为什么被折叠?



