图的广度优先搜索

输入:
4
4
3 0 0 0
0 4 5 0

0 1 0 1
0 0 0 4

输入第一行:矩阵的行数
输入第二行:矩阵的列数

接下来输入的是矩阵的形式

import java.util.*;
public class Solution {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		Stack<Integer> stackI = new Stack<>();
		Stack<Integer> stackJ = new Stack<>();
		while(scan.hasNext()){
			int col = scan.nextInt();
			int row = scan.nextInt();
			List<Integer> list = new ArrayList<>();
			int[][] index = {{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1}}; //8个可搜寻的方向
			int[][] num = new int[row][col]; //图像矩阵
			int[][] haveSearch = new int[row][col]; //标记次位是否被搜寻过
			//矩阵元素的输入
 			for(int i = 0; i < row; i++){
				for(int j = 0; j < col; j++){
					num[i][j] = scan.nextInt();
				}
			}
 		   for(int i = 0; i < row; i++){
 				for(int j = 0; j < col; j++){
 					//主图找每个单元阵起始点搜索
 					//不为0该元素可做起始点
 					while(num[i][j] != 0){
 	 					int directionFlag = 0;//找到方向该标记位为1,否则为0
 	 					//八邻域找可搜寻方向
 	 					if(haveSearch[i][j] == 0){	
	 						stackI.push(i);
	 						stackJ.push(j);
	 						haveSearch[i][j] = 1;
 	 					}
	 					for(int k = 0; k < 8; k++){
	 						int indexI = i + index[k][0];
	 						int indexJ = j + index[k][1];
	 						if( indexI >= 0 && indexI < row && indexJ >= 0 && indexJ < col
	 								&& num[indexI][indexJ] != 0 && haveSearch[indexI][indexJ] == 0){
	 							haveSearch[indexI][indexJ] = 1;
	 							stackI.push(indexI);
	 							stackJ.push(indexJ);
	 						    i = indexI;
	 						    j = indexJ;
	 							directionFlag = 1;
	 							break;
	 						}
	 					}
	 					if(directionFlag == 0){
	 						i = stackI.pop();
	 						j = stackJ.pop();
	 					}
 					}
 				}
 			}
		}
	}
}

思路:

1,建立一个二维矩阵存储矩阵数字,建立标记二维矩阵(1为该矩阵被搜索,0为未被搜索),建立栈压入每次搜索的探测点
2,建立搜索方向数组,视情况不同建立不同,建立八方向

3,确定搜索起始点,如果此点标记为0,压入栈中,改标记为1,否则不进行任何操作
4,向八个方向循环探测,如果某个方向可搜索,搜索坐标变换,搜索起始点变为此点,跳出循环
5,否则,出栈跳转到3
6,一旦搜索坐标满足变换结束此轮搜索

            
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值