更多关于刷题的内容欢迎订阅我的专栏华为刷题笔记
该专栏题目包含两部分:
100 分值部分题目
200 分值部分题目
所有题目都会陆续更新,订阅防丢失
题目描述
给一个字符串和一个 二维字符数组,如果该字符串存在于该数组中,则按字符串的字符顺序输出字符串每个字符所在单元格的位置下标字符串,如果找不到返回字符串“N”
1.需要按照字符串的字符组成 顺序搜索,且搜索到的位置必须是相邻单元格,其中"相邻单元格"是指那些水平相邻或垂直相邻的单元格。
2.同一个单元格内的字母不允许被重复使用。
3.假定在数组中最多只存在一个可能的匹配。
输入描述
第1行为一个数字N指示二维数组在后续输入所占的行数。
第2行到第N+1行输入为一个二维大写字符数组,每行字符用半角,分割。
第N+2行为待查找的字符串,由大写字符组成。
维数组的大小为N*N,0<N<=100.
单词长度K,0<K<1000。
输出描述
输出一个位置下标字符串,拼接格式为:第1个字符行下标+“,”+第1个字符列下标+”,”+第2个字符行下标+“”+第2个字符列下标.….-+“”+第N个字符行下标+””+第N个字符列下标。
示例1
输入
4
A,C,C,F
C,D,E,D
B,E,S,S
F,E,C,A
ACCESS
输出
0,0,0,1,0,2,1,2,2,2,2,3
说明
ACCESS分别对应二维数组的[0,0][0,1][0,2][1,2][2,2][2,3]下标位置。
题解
源码 java
import java.util.ArrayList;
import java.util.List;
public class FindWord {
static Input input;
static {
input = new Input("4\n" +
"A,C,C,F\n" +
"C,D,E,D\n" +
"B,E,S,S\n" +
"F,E,C,A\n" +
"ACCESS");
}
public static boolean found = false;
static String word = "";
static List<Point> result = new ArrayList<>();
public static void main(String[] args) {
int n = Integer.parseInt(input.nextLine());
char[][] chs = new char[n][n];
for (int i = 0; i < n; i++) {
String[] split = input.nextLine().split(",");
for (int j = 0; j < n; j++) {
chs[i][j] = split[j].charAt(0);
}
}
word = input.nextLine();
for (int i = 0; i < word.length(); i++) {
for (int j = 0; j < word.length(); j++) {
dfs(chs, new Point(i,j), 0);
}
}
}
static int[][] direction = {{0,1}, {0,-1}, {1,0}, {-1,0}};
static void dfs(char[][] chs, Point p, int count) {
if (found) {
return;
}
if (p.x < 0 || p.y < 0 || p.x >= chs.length || p.y >= chs[0].length) {
return;
}
if (chs[p.x][p.y] == word.charAt(count)) {
result.add(new Point(p.x,p.y));
if (result.size() == word.length()) {
found = true;
List<String> list = new ArrayList<>();
for (int i = 0; i < result.size(); i++) {
Point point = result.get(i);
list.add(point.x+"");
list.add(point.y+"");
}
System.out.println(String.join(",", list));
}
} else {
return;
}
for (int i = 0; i < direction.length; i++) {
char ch = chs[p.x][p.y];
chs[p.x][p.y] = '#';
dfs(chs, new Point(p.x + direction[i][0], p.y + direction[i][1]), count+1);
chs[p.x][p.y] = ch;
}
}
static class Point{
public int x;
public int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
}