LintCode 199: Judge Connection

本文探讨了一个算法问题,即如何判断二维矩阵中所有相同特定值的元素是否相互连接。通过使用广度优先搜索(BFS)算法,我们能够有效地检查所有指定值的元素是否形成一个连续的区域。

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;
    }
};

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值