模拟对对碰检测相邻元素代码

闲来无事,模拟写了一个对对碰检测相邻元素的代码。快下班了,不细说,直接贴代码。不足之处请指正,另请教各位大侠有没更好的算法,望高手优化。

第一次发帖,勿拍微笑

public class Test{
	//测试
	//private int[][] source=new int[][]{{0,0,0,0,0,0},{0,2,2,1,1,0},{0,4,2,1,1,0},{0,2,2,4,1,0},{0,4,1,2,1,0},{0,0,0,0,0,0}};
	private int[][] source;
	private int col,row;
	static int[][] direction=new int[][]{{-1,0},{1,0},{0,-1},{0,1}};
	
	public Test(int m,int n){
		this.col=m;
		this.row=n;
	}
	//产生一个二维数组
	private int[][] generateArray(){
		//在产生的数组外面加一圈用0填充
		source=new int[col+2][row+2];
		for(int i=1;i<=col;i++){
			for(int j=1;j<=row;j++){
				Random rnd=new Random();
				int num=0;
				while (num==0) {
					num=rnd.nextInt(5);					
				}
				source[i][j]=num;	
			}
		}
		
		return source;
	}
	//输出原始二维数组
	private void OutputArray(){
		if(source.length==0){
			return;
		}
		for(int i=0;i<col+2;i++){
			for(int j=0;j<row+2;j++){
				System.out.print(source[i][j]+"\t");
			}
			System.out.println("\n");
		}		
	}	
	//检测相邻元素
	public void testNeigbor() {
		Stack<Integer> stack=new Stack<Integer>();
		Stack<Integer> result=new Stack<Integer>();
		//逐个元素检查是否有相邻的元素
		for(int i=1;i<col+1;i++){
			for(int j=1;j<row+1;j++){
				if(source[i][j]==0) continue; 
				//将要检测的元素压入结果堆栈
				result.push(i*(row+2)+j);
				int x=i, y=j;
				int tmp;
				boolean hasNext=false;
				do{
					tmp=source[x][y];
					source[x][y]=0;
					//检测上下左右是否有值相同的,有的话压入两个堆栈
					int a,b,v;
					for(int z=0;z<4;z++){
						a=x+direction[z][0];
						b=y+direction[z][1];
						v=source[a][b];
						if(v==0) continue;
						if(v==tmp){
							stack.push(a*(row+2)+b);
							result.push(a*(row+2)+b);
						}
					}
					//检测完一个元素后,临时堆栈里面的最后一个元素出栈
					if(stack.size()>0){
						int po=stack.pop();
						x=po/(row+2);
						y=po%(row+2);
						hasNext=true;
					}else {
						hasNext=false;
					}
				}while(hasNext);			
				printStack(result);
			}
		}		
	}
	//输出堆栈中存储的下标
	public void printStack(Stack<Integer> stack, int count){
		if(stack.size()<count){
			stack.clear();
			return ;
		}
		int x,y;
		while (stack.size()>0) {
			int po=stack.pop();
			x=po/(row+2);
			y=po%(row+2);
			System.out.print("["+x+","+y+"]\t");			
		}
		System.out.print("\n");
	}
	//简化堆栈输出
	public void printStack(Stack<Integer> stack){
		printStack(stack,3);		
	}
	
	public static void main(String[] args){
		Test test=new Test(4,4);
		test.generateArray();
		test.OutputArray();
		test.testNeigbor();
	}
}
 
结果图如下:

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值