当前位置:网站首页>寻找矩阵中“块“的个数(BFS)
寻找矩阵中“块“的个数(BFS)
2022-04-22 05:34:00 【韩跳跳、】
题目描述
给出一个mxn的矩阵,矩阵中的元素为0或1。称位置(x,y)与其上下左右四个位置(x,y+1)、(x,y-1)、(x+1,y)、(x-1,y)是相邻的。如果矩阵中有若干个1是相邻的(不必两两相邻),那么称这些1构成了一个“块”。求给定的矩阵中“块”的个数。
【输入样例】
6 7
0 1 1 1 0 0 1
0 0 1 0 0 0 0
0 0 0 0 1 0 0
0 0 0 1 1 1 0
1 1 1 0 1 0 0
1 1 1 1 0 0 0
【输出样例】
4
解题思路
用广度优先搜索来遍历一个“块”,并将其标记为1,标记后就不会再被遍历了,一共遍历几次,就代表有几个“块”。
代码实现
import java.util.*;
public class Main {
//增量
static int n;
static int m;
static int[] X={
0,0,-1,1};//上 下 左 右
static int[] Y={
-1,1,0,0};//上 下 左 右
static int[][] matrix;//矩阵
static boolean[][] visted;//用于标记某点是否被访问
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
n=scan.nextInt();//n行
m= scan.nextInt();//m列
visted=new boolean[n][m];
matrix=new int[n][m];
//输入矩阵
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j]= scan.nextInt();
}
}
//依次搜索矩阵中的每个点(当然条件是之前没有被搜索过,且该位为0)
int count=0;
for (int x = 0; x < n; x++) {
for (int y = 0; y < m; y++) {
if(!visted[x][y]&&matrix[x][y]==1){
bfs(x,y); //本题中bfs的结果是,下一个遇到的“1块”被标记为已访问
count++;
}
}
}
System.out.println(count);
scan.close();
}
public static void bfs(int x,int y){
node start=new node(x,y);
visted[x][y]=true;
Deque<node> que=new LinkedList<>();
que.offer(start);
while(!que.isEmpty()){
node now=que.poll();
for(int i=0;i<4;i++){
int newx=now.x+X[i];
int newy=now.y+Y[i];
if(check(newx,newy)){
visted[newx][newy]=true;
node next=new node(newx,newy);
que.offer(next);
}
}
}
}
public static boolean check(int x,int y){
//数组越界
if(x<0||x>=n||y<0||y>=m){
return false;
}
//已经被访问过了
if(visted[x][y]||matrix[x][y]==0){
return false;
}
return true;
}
}
class node{
int x;
int y;
node(){
}
node(int x,int y){
this.x=x;
this.y=y;
}
}

版权声明
本文为[韩跳跳、]所创,转载请带上原文链接,感谢
https://blog.csdn.net/han_tiao_tiao/article/details/123309613
边栏推荐
猜你喜欢
随机推荐
单机部署redis主从与哨兵模式(一主两从三哨兵)
Kaggle_ Detailed explanation of NBME NLP competition baseline (2)
imencode 源码解读
数的范围( 二分 经典模板题目)
C WinForm about incomplete display of listview
stl alloc 空间分配器 代码解析
关于form表单点击submit按钮后,页面自动刷新的问题解决
Enquête JVM
MySQL transaction
再见2020,2021我来了
Single machine deployment redis master-slave and sentinel mode (one master, two slave and three sentinels)
JVM探究
MySQL command
力扣876. 链表的中间结点
最长上升子序列(lis)
CopyOnWriteArrayList的使用场景
【转】MySQL:InnoDB一棵B+树可以存放多少行数据?
线程池的几个常识
我常用的开发软件
Strong connected component of "tarjan" undirected graph








