1582. 二进制矩阵中的特殊位置

地址:

力扣icon-default.png?t=LBL2https://leetcode-cn.com/problems/special-positions-in-a-binary-matrix/

题目:

给你一个大小为 rows x cols 的矩阵 mat,其中 mat[i][j] 是 0 或 1,请返回 矩阵 mat 中特殊位置的数目 。

特殊位置 定义:如果 mat[i][j] == 1 并且第 i 行和第 j 列中的所有其他元素均为 0(行和列的下标均 从 0 开始 ),则位置 (i, j) 被称为特殊位置。

示例 1:

输入:mat = [[1,0,0],
            [0,0,1],
            [1,0,0]]
输出:1
解释:(1,2) 是一个特殊位置,因为 mat[1][2] == 1 且所处的行和列上所有其他元素都是 0


示例 2:

输入:mat = [[1,0,0],
            [0,1,0],
            [0,0,1]]
输出:3
解释:(0,0), (1,1) 和 (2,2) 都是特殊位置


示例 3:

输入:mat = [[0,0,0,1],
            [1,0,0,0],
            [0,1,1,0],
            [0,0,0,0]]
输出:2


示例 4:

输入:mat = [[0,0,0,0,0],
            [1,0,0,0,0],
            [0,1,0,0,0],
            [0,0,1,0,0],
            [0,0,0,1,1]]
输出:3

提示:

rows == mat.length
cols == mat[i].length
1 <= rows, cols <= 100
mat[i][j] 是 0 或 1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/special-positions-in-a-binary-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:

依次扫描每一行,如果改行元素超过1个的值大于1,跳过改行
否则,记录对应列坐标
依次遍历该列的其他元素,超过1跳出,否则自增1

方法一、逐行扫描再基于找到的该行元素进行列遍历

int numSpecial(int** mat, int matSize, int* matColSize){
    int r=matSize;
    int c=matColSize[0];
    int cnt=0;
    int r_cnt=0, c_cnt=0;
    int r_spe_cidx=-1;
    int i,j,k;
    bool isfound=false;

    for(i=0; i<r; i++)      // search each row
    {
        isfound=false;
        r_cnt = 0;

        for(j=0; j<c; j++)  // check if we can find only one elements=1, record its column idx
        {
            if(mat[i][j] == 1)
            {
                r_cnt++;
                if(r_cnt > 1)
                    break;
                    
                r_spe_cidx=j; 
            }
        }

        if(r_cnt == 1) // we found special colunm idx in this row, check other elements in this column
        {
            c_cnt=0;
            for(k=0; k<r; k++)
            {
                if(mat[k][r_spe_cidx] == 1)
                {   
                    c_cnt++;
                    if(c_cnt > 1)
                    {
                        isfound=false;
                        break;
                    }
                }
            }

            if(k==r)
                isfound=true;
        }

        if(isfound == true)
            cnt++;
    }
    
    return cnt;
}

查看更多刷题笔记

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值