智乐活,查找一片区域

Java代码:

class A{
	int x;
	int y;
	A(int x,int y){
		this.x=x;
		this.y=y;
	}
	 public int hashCode() {
	        int result = 17;
	        result = 37 * result + x;
	        result = 37 * result +y;
	        return result;
	    }
	 public boolean equals(Object o){
	        return o instanceof A && (x == ((A)o).x)&&(y==((A)o).y);
	    }
}

public class TestA {
	
	static void find_connected(int[][]array,int n,int x,int y){
		if(x<0||y<0||x>=n||y>=n) return;
	    int data=array[x][y];
	    A tmp=new A(x,y);
	    Queue<A> q=new LinkedList<>();
	    ArrayList<A>list=new ArrayList<A>();
	    int flag[][]=new int[n][n];
	    flag[x][y]=1;
	    q.offer(tmp);
	    while(q.size()!=0){
	    	tmp=q.poll();
	    	list.add(tmp);
	    	x=tmp.x;
	    	y=tmp.y;
	    	if(x-1>=0 && flag[x-1][y]==0 && array[x-1][y]==data) {q.offer(new A(x-1,y));flag[x-1][y]=1;}
	    	if(y-1>=0 && flag[x][y-1]==0 && array[x][y-1]==data) {q.offer(new A(x,y-1));flag[x][y-1]=1;}
		    if(x+1<n && flag[x+1][y]==0 && array[x+1][y]==data)  {q.offer(new A(x+1,y));flag[x+1][y]=1;}
		    if(y+1<n && flag[x][y+1]==0 && array[x][y+1]==data)  {q.offer(new A(x,y+1));flag[x][y+1]=1;}
	    }
	    for(int i=0;i<list.size();i++){
	    	tmp=list.get(i);
	    	if(i!=list.size()-1)
	    	    System.out.print("("+tmp.x+","+tmp.y+")"+",");
	    	else
	    		System.out.print("("+tmp.x+","+tmp.y+")");
	    }
	}

	

	public static void main(String[] args) {
		int array[][]={
				{13,67,6,3,11},
				{13,13,5,11,8},
				{10,10,10,41,41},
				{2,2,10,10,33},
				{13,10,13,22,34}
				};
		find_connected(array,5,2,1);

	}

}

  

原文地址:https://www.cnblogs.com/mlz-2019/p/5043559.html