Word Search
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example:
1 | board = |
思路:回溯法来解决,定义一个二维的flag数组来表示每一个点是否已经被找过,还没找过标志为false,这个点已经找过标志位true。然后利用回溯法的思想:首先在二维的board中找到和给定的字符串第一个字符相等的位置,然后从这个位置出发,再从各个方向查找(此时就可以用到递归来查找),在查找过程中越过边界或者遇到已经找过的点,就标记为false,当前路径下不再查找该点,最后直到遍历到给定字符串的最后一个字符,这时候,我们可以确定,之前的所有字符都在board中找到,存在连续的表示,所以当最后一个字符找完以后如果全部找到就返回true,否则返回false.。
代码如下:
1 | class Solution { |