The topic is from LeetCode
Other solutions or source code can be accessed: tongji4m3
description
Given a two-dimensional grid and a word, find out whether the word exists in the grid.
Words must be in alphabetical order and formed by letters in adjacent cells, where "adjacent" cells are those that are adjacent horizontally or vertically. Letters in the same cell are not allowed to be reused.
Example:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
给定 word = "ABCCED", 返回 true
给定 word = "SEE", 返回 true
给定 word = "ABCB", 返回 false
prompt:
board 和 word 中只包含大写和小写英文字母。
1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
Ideas
Depth first search, in the same search, change the searched to * or other signs, and then restore it after searching
for i in M:
for j in N:
if dfs(i,j,0) return true; //如果找到了就直接结束,找不到就继续找
dfs(int i,int j,int index)
{
if(board[i][j]!=word[index]) return false;
if(index==word.length-1) return true;
temp=board[i][j];
board[i][j]='*';//标记为已访问
如果符合边界条件,dfs(他的上下左右,index+1);
board[i][j]=temp;//这次深搜结束,恢复
}
detail
- If you find it, you can return directly without entering the two-dimensional array. If you can't find it, you must continue, so pay attention to the conditions
- In dfs, the condition of return is to return false when all four directions are not found
Code
public boolean exist(char[][] board, String word)
{
if (board.length == 0)
{
return false;
}
int m = board.length, n = board[0].length;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (dfs(board, word, i, j, 0))
{
return true;
}
}
}
return false;
}
private boolean dfs(char[][] board, String word, int i, int j, int index)
{
if (board[i][j] != word.charAt(index))
{
return false;
}
if (index == word.length() - 1)
{
return true;
}
char temp = board[i][j];
//标记为已访问
board[i][j] = '*';
boolean result = false;
if (i - 1 >= 0)
{
result = dfs(board, word, i - 1, j, index + 1);
}
if (i + 1 < board.length)
{
result = result || dfs(board, word, i + 1, j, index + 1);
}
if (j - 1 >= 0)
{
result = result || dfs(board, word, i, j - 1, index + 1);
}
if (j + 1 < board[0].length)
{
result = result || dfs(board, word, i, j + 1, index + 1);
}
//这次深搜结束,恢复
board[i][j] = temp;
return result;
}