藍橋-深度優先求連通性

給定一個方陣,定義連通:上下左右相鄰,並且值相同。
可以想象成一張地圖,不同的區域被塗以不同顏色。
輸入:
整數N, (N<50)表示矩陣的行列數
接下來N行,每行N個字符,代表方陣中的元素
接下來一個整數M,(M<1000)表示詢問數
接下來M行,每行代表一個詢問,
格式爲4個整數,y1,x1,y2,x2,
表示(第y1行,第x1列) 與 (第y2行,第x2列) 是否連通。
連通輸出true,否則false

例如:
10
0010000000
0011100000
0000111110
0001100010
1111010010
0000010010
0000010011
0111111000
0000010000
0000000000
3
0 0 9 9
0 2 6 8
4 4 4 6

程序應該輸出:
false
true
true
 

import java.util.Scanner;

public  class Lian_tong {
public static boolean lian_tong(char[][]data,int x1,int y1,int x2,int y2) {
if(x1==x2&&y1==y2)
return true;
char old=data[x1][y1];
//避免又回到原來,對訪問過的點進行標記
data[x1][y1]='*';
try {
if(x1<data.length-1&&data[x1+1][y1]==old&&lian_tong(data,x1+1,y1,x2,y2)) {
return true;
}
if(y1<data.length-1&&data[x1][y1+1]==old&&lian_tong(data,x1,y1+1,x2,y2)) {
return true;
}
if(x1>0&&data[x1-1][y1]==old&&lian_tong(data,x1-1,y1,x2,y2)) {
return true;
}
if(y1>0&&data[x1][y1-1]==old&&lian_tong(data,x1,y1-1,x2,y2)) {
return true;
}	
}
finally {
data[x1][y1]=old;
}
return false;	
}

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
//n:矩陣的行列式
int n=Integer.parseInt(sc.nextLine());
//輸入n行n列,用二維數組接收
char [][] data=new char[n][];
for(int i=0;i<n;i++){
data[i]=sc.nextLine().toCharArray();
}
//計算n次是否連通
int m=Integer.parseInt(sc.nextLine());
for(int i=0;i<m;i++) {
String []s=sc.nextLine().split(" ");
int x1=Integer.parseInt(s[0]);
int y1=Integer.parseInt(s[1]);
int x2=Integer.parseInt(s[2]);
int y2=Integer.parseInt(s[3]);
System.out.println(lian_tong(data,x1,y1,x2,y2));
}	
}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章