【Leetcode】【Medium】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.

For example,
Given board =

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

解题思路:

使用深度优先搜索的方法,从二维数组中的每个点出发,向上下左右进行延伸,根据判定条件及时判断;

解题步骤:

1、写一个主函数:

  (1)获得二维数组的行列大小;

  (2)遍历所有二维数组元素,对每个元素作为搜索起点,调用递归函数;

2、写一个递归函数,参数为:二维数组(引用)、待匹配的字符串(c字符串形式方便)、当前运动到的坐标值x和y、二维数组大小m和n;

  (1)终止判定条件:x和y无效、当前运动到的字符不是字符串下一个字符;

  (2)如果已经到达匹配字符串末尾,返回true

  (3)暂时将当前运动到的坐标字符置换为‘\0‘,因为要做出标记,以免重复折返运动;

  (4)调用4个递归函数,分别运动到当前运动字符的上下左右四周,并判定;

  (5)如果4个递归函数都false,则换回被置换的‘\0‘,返回false;

代码:

 1 class Solution {
 2 public:
 3      bool exist(vector<vector<char> > &board, string word) {
 4         m = board.size();
 5         n = board[0].size();
 6         for(int x = 0; x < m; x++) {
 7             for(int y = 0; y < n; y++) {
 8                 if(isFound(board, word.c_str(), x, y))
 9                     return true;
10             }
11         }
12         return false;
13     }
14
15 private:
16     int m;
17     int n;
18     bool isFound(vector<vector<char> > &board, const char* w, int x, int y) {
19         if(x < 0 || y < 0 || x >= m || y >= n || *w != board[x][y])
20             return false;
21         if(*(w + 1) == ‘\0‘)
22             return true;
23         char t = board[x][y];
24         board[x][y] = ‘\0‘;
25         if(isFound(board, w + 1, x - 1, y) ||
26             isFound(board, w + 1, x + 1, y) ||
27             isFound(board, w + 1, x, y - 1) ||
28             isFound(board, w + 1, x, y + 1))
29             return true;
30         board[x][y]=t;
31         return false;
32     }
33 };
时间: 2024-08-28 19:51:12

【Leetcode】【Medium】word search的相关文章

【leetcode刷题笔记】Validate Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys

【leetcode刷题笔记】Search a 2D Matrix

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous ro

【leetcode刷题笔记】Recover Binary Search Tree

Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note:A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? 题解:需要找到二叉搜索树中乱序的两个节点,并把它们交换回来

【leetcode刷题笔记】Search in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplic

【leetcode刷题笔记】Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space cha

【leetcode刷题笔记】Unique Binary Search Trees II

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For example,Given n = 3, your program should return all 5 unique BST's shown below. 1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2 3 题解:递归的枚举1~n的每个节点为根节点,然后递归

【leetcode刷题笔记】Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 题解:开始想到的方法比较偷懒,直接遍历一遍数组,把每个ListNode对应的值放到数组里面,然后把数组转换成BST,想来这个题的本意肯定不是这样. 自己也想到了bottom-up的方法,但是没想明白怎么个bottom-up法,真的是昨天做梦都在想=.= 今天早上终于弄懂了,用递归

【leetcode刷题笔记】Search in Rotated Sorted Array II

Follow up for "Search in Rotated Sorted Array":What if duplicates are allowed? Would this affect the run-time complexity? How and why? Write a function to determine if a given target is in the array. 题解:如果没有重复的元素,那么就可以根据target是否在某一半而扔掉另外一半.但是如果有

【leetcode刷题笔记】Substring with Concatenation of All Words

You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters. For example, given:S: "b

【leetcode刷题笔记】Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example:Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 题解:深度优先搜索.用resul