找到它
2025-10-27 本文已影响0人
何以解君愁
找到它是个小游戏,你需要在一个矩阵中找到给定的单词
假设给定单词HELLOWORLD,在矩阵中只要能找HELLOWORLD就算通过
注意区分英文字母大小写,并且你只能上下左右行走,不能走回头路
输入描述:
输入第一行包含两个整数N M (0 < N, M < 21)
分别表示N行M列的矩阵
第二行是长度不超过100的单词W
在整个矩阵中给定单词W只会出现一次
从第3行到第N+2是只包含大小写英文字母的长度为M的字符串矩阵
输出描述
如果能在矩阵中连成给定的单词,则输出给定单词首字母在矩阵中的位置为第几行第几列
否则输出 NO
/**
*HELL
*LROWO
*D
*/
import java.util.*;
public class Main{
static boolean found = false;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int col = sc.nextInt();
int row = sc.nextInt();
sc.nextLine();
//目标字符
String target = sc.nextLine();
//字符数组
char[][] check = new char[col][row];
//接收字符数组
for(int i = 0;i < col;i++){
String s = sc.nextLine();
for(int j = 0;j < row;j++){
check[i][j] = s.charAt(j);
}
}
boolean[][] checkFound = new boolean[col][row];
for(int i = 0;i < col;i++){
for(int j = 0;j < row;j++){
if(target.charAt(0) == check[i][j]){
checkFound[i][j] = true;
backTracking(check,checkFound,i,j,target,0,col,row);
checkFound[i][j] = false;
if(found){
System.out.print((i + 1) +" "+ (j + 1));
return;
}
}
}
}
if(!found){
System.out.println("NO");
}
}
public static void backTracking(char[][] check,boolean[][] checkFound,int i,int j,String target,int index,int col,int row){
if(index == target.length() - 1){
found = true;
return;
}
if(i - 1 >= 0&&!checkFound[i - 1][j]&&check[i - 1][j] == target.charAt(index + 1)){
checkFound[i - 1][j] = true;
backTracking(check,checkFound,i-1,j,target,index+1,col,row);
checkFound[i - 1][j] = false;
}
if (found) return;
if(i + 1 < col&&!checkFound[i + 1][j]&&check[i + 1][j] == target.charAt(index + 1)){
checkFound[i + 1][j] = true;
backTracking(check,checkFound,i+1,j,target,index+1,col,row);
checkFound[i + 1][j] = false;
}
if (found) return;
if(j - 1 >= 0&&!checkFound[i][j - 1]&&check[i][j - 1] == target.charAt(index + 1)){
checkFound[i][j - 1] = true;
backTracking(check,checkFound,i,j-1,target,index+1,col,row);
checkFound[i][j - 1] = false;
}
if (found) return;
if(j + 1 < row&&!checkFound[i][j+1]&&check[i][j+1] == target.charAt(index + 1)){
checkFound[i][j+1] = true;
backTracking(check,checkFound,i,j+1,target,index+1,col,row);
checkFound[i][j+1] = false;
}
}
}