Java solves the problem of special positions in binary matrices
01 Question
Give you a matrix of sizerows x cols
, where is or , please return the number of special positions in the matrix**. mat
mat[i][j]
0
1
mat
Special Position Definition: Ifmat[i][j] == 1
and line i
and line j
All other elements in the column are 0
(row and column subscripts both start from 0 ), then Position(i, j)
is called a special position.
Example 1:
输入:mat = [[1,0,0],
[0,0,1],
[1,0,0]]
输出:1
解释:(1,2) 是一个特殊位置,因为 mat[1][2] == 1 且所处的行和列上所有其他元素都是 0
Example 2:
输入:mat = [[1,0,0],
[0,1,0],
[0,0,1]]
输出:3
解释:(0,0), (1,1) 和 (2,2) 都是特殊位置
Example 3:
输入:mat = [[0,0,0,1],
[1,0,0,0],
[0,1,1,0],
[0,0,0,0]]
输出:2
Example 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
hint:
rows == mat.length
cols == mat[i].length
1 <= rows, cols <= 100
mat[i][j]
is0
or1
02 Knowledge points
- Two-dimensional array
03 My solution
public class shuzu05 {
public static void main(String[] args) {
//测试数据
int[][] mat=new int[][] {
{
1,0,0},
{
0,1,0},
{
0,0,1}
};
System.out.println(numSpecial(mat));
}
public static int numSpecial(int[][] mat) {
int count=0;
int m=mat.length;//记录排的数量
int n=mat[0].length;//记录列的数量
for (int i = 0; i < m; i++) {
boolean flag=false;//用于标记是否满足第一条件
for (int j = 0; j <n; j++) {
if (mat[i][j]==1) {
flag=true;
//当满足第一条件执行,第二条件
}
if (flag) {
//目的是判断同一行是否有满足第一条件的数
for (int k1 = 0; k1 < m; k1++) {
if (mat[k1][j]==1&&k1!=i) {
flag=false;
break;
}
}
//目的是判断同一列是否有满足第一条件的数
for (int k2 = 0; k2 < n; k2++) {
if (mat[i][k2]==1&&k2!=j) {
flag=false;
break;//flag要修改,还要退出循环
}
}
//如果前两个条件都不满足,则说明同一行和同一列都没有mat[i][j]=1,flag的值依旧是true,则count+1
}
if (flag) {
count++;
}
}
}
return count;
}
}