(1)Lct準備研究一個名為“Link - Cut - Tree”的演算法,他認為這個演算法很美,所以他每天都說“lcttxdy”。有一天,他挑了一個n?m棋盤,但這讓他很奇怪的是棋盤上的每一個棋子都有一個小字母,他想知道有多少個大小寫字母連在一起可以構成‘lcttxdy’。(注意:只有當一個字母在上、下、左、右、左上、左下、右上和右下時,我們稱這兩個字母是連在一起的)
輸入
第一行包含一個整數t(1≤t≤100)——輸入中的測驗用例的數量。
每個測驗用例的第一行包含兩個整數n和m——棋盤格的長度和寬度(1≤n,m≤100)
接下來的n行每一行包含m個字母,它們都是英文小寫字母
輸出
對于每種情況,輸出兩行:
在第一行輸出“YES”或“NO”——查找或不查找“lcttxdy”
在第二行輸出“lcttxdy”的數目。如果沒有找到列印-1
求代碼
uj5u.com熱心網友回復:
public static void main(String[] args) {
F(10,10);
}
//n m 棋盤
public static void F(int n,int m) {
char[][] charset=new char[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
charset[i][j]= (char)(Math.random()*26+97);
System.out.print(charset[i][j]);
}
System.out.println();
}
select(new char[][] {new char[] {'l','c','t','t','x','d','y'}});
}
static LinkedList<String> string1=new LinkedList<String>();
//1 棋盤 x y a當前下標 cha 查找的字符
public static void Seach(char[][] qi,int x,int y,int a,char[] cha) {
if(a==cha.length-1) {
System.out.println("成功。。。。。。");
string1.forEach(e->System.out.println(e));
System.exit(0);
return ;
}
String ok=isok(qi,x,y,cha[a]);
if(ok!=null) {
String [] s=ok.split(",");
string1.add(ok);
Seach(qi,Integer.parseInt(s[0]),Integer.parseInt(s[1]),a+1,cha);
string1.removeLast();
}
}
public static void select(char[][] qi) {
for (int i = 0; i < qi.length; i++) {
for (int j = 0; j < qi[0].length; j++) {
Seach(qi,i,j,0,new char[] {'l','c','t','t','x','d','y'});
}
}
}
//查詢 并回傳 坐標
public static String isok(char[][] qi,int x,int y,char a) {
if(ishh(qi,x+1,y,a)) return (x+1)+","+y;
if(ishh(qi,x-1,y,a)) return (x-1)+","+y;
if(ishh(qi,x-1,y+1,a)) return (x-1)+","+(y+1);
if(ishh(qi,x-1,y-1,a)) return (x-1)+","+(y-1);
if(ishh(qi,x+1,y+1,a)) return (x+1)+","+(y+1);
if(ishh(qi,x+1,y-1,a)) return (x+1)+","+(y-1);
if(ishh(qi,x,y+1,a)) return x+","+(y+1);
if(ishh(qi,x,y-1,a)) return x+","+(y-1);
return null;
}
public static boolean ishh(char [][]qi,int x,int y,char a) {
try {
return qi[x][y]==a;
} catch (Exception e) {
return false;
}
} select 改成上面隨機生成的就行了 不過看臉 哎。。。。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/44406.html
標籤:Java SE
