闲来无事,模拟写了一个对对碰检测相邻元素的代码。快下班了,不细说,直接贴代码。不足之处请指正,另请教各位大侠有没更好的算法,望高手优化。
第一次发帖,勿拍
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();
}
}
结果图如下:
![](https://img-my.csdn.net/uploads/201208/24/1345802075_1613.gif)