问题:
难度:easy
说明:
给出二维数组 char[][],和需要查找的字符串,如果存在返回 true,查找的时候可以查找上下左右不重复的 串,其实这个已经做过更复杂的了。
问题链接:https://leetcode.com/problems/word-search/
相关问题:
Word Search II(二维数组找相同字符串):https://blog.csdn.net/qq_28033719/article/details/107055702
输入范围:
board
andword
consists only of lowercase and uppercase English letters.1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
输入案例:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
我的代码:
如果用循环做,处理栈也很麻烦(放入坐标),所以用递归最好解决,然后判断上下左右四个方向,还有 visited 表,当然也可以用board 然后输入一个非 26 位字母的字符当做判断(如果字符串是任意字符就不行了)。
class Solution {
private static int x = 0;
private static int y = 0;
private static int len = 0;
private static boolean flag = false;
private static char cancle = '-';
public boolean exist(char[][] board, String word) {
char[] chs = word.toCharArray();
len = chs.length - 1;
flag = false;
x = board.length;
y = board[0].length;
for(int i = 0;i < x;i ++)
for(int j = 0;j < y;j ++) {
helper(board, i, j, chs, 0);
if(flag) return true;
}
// 返回标记
return flag;
}
public void helper(char[][] board, int i, int j, char[] chs, int index) {
// 如果已经找到就立即返回
if(flag) return;
if(board[i][j] == chs[index]) {
// 将本节点浏览改为 cancle
char temp = board[i][j];
board[i][j] = cancle;
// 如果找到就把标记改为 true
if(index == len) flag = true;
index ++;
// 找上下左右没有浏览过和没越界的元素
if(i - 1 >= 0 && board[i - 1][j] != cancle) helper(board, i - 1, j, chs, index);
if(i + 1 < x && board[i + 1][j] != cancle) helper(board, i + 1, j, chs, index);
if(j - 1 >= 0 && board[i][j - 1] != cancle) helper(board, i, j - 1, chs, index);
if(j + 1 < y && board[i][j + 1] != cancle) helper(board, i, j + 1, chs, index);
// 处理完毕,本节点浏览改为 原来字符
board[i][j] = temp;
}
}
}
使用visited代码:
class Solution {
private static int x = 0;
private static int y = 0;
private static int len = 0;
private static boolean flag = false;
public boolean exist(char[][] board, String word) {
char[] chs = word.toCharArray();
len = chs.length - 1;
flag = false;
x = board.length;
y = board[0].length;
boolean[][] visited = new boolean[x][y];
for(int i = 0;i < x;i ++)
for(int j = 0;j < y;j ++) {
helper(board, i, j, chs, 0, visited);
if(flag) return true;
}
return flag;
}
public void helper(char[][] board, int i, int j, char[] chs, int index, boolean[][] visited) {
// 如果已经找到就立即返回
if(flag) return;
// 将本节点浏览改为 true
visited[i][j] = true;
if(board[i][j] == chs[index]) {
if(index == len) flag = true;
index ++;
// 找上下左右没有浏览过和没越界的元素
if(i - 1 >= 0 && !visited[i - 1][j]) helper(board, i - 1, j, chs, index, visited);
if(i + 1 < x && !visited[i + 1][j]) helper(board, i + 1, j, chs, index, visited);
if(j - 1 >= 0 && !visited[i][j - 1]) helper(board, i, j - 1, chs, index, visited);
if(j + 1 < y && !visited[i][j + 1]) helper(board, i, j + 1, chs, index, visited);
}
// 处理完毕,本节点浏览改为 false
visited[i][j] = false;
}
}