Leetcode之Word Search 问题

来源:互联网 发布:sql 查询表的所有列名 编辑:程序博客网 时间:2024/06/06 01:27

问题描述:

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 =

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

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

问题来源:Word Search (详细地址:https://leetcode.com/problems/word-search/description/)

思路分析:这道题很明显是一个递归问题,需要判断“上下左右”四个方位的情况才能找到答案,只要这四个方位中找到一个的话我们就能得出正确结果了,相反如果四个方位都没有的话,那么返回的结果就是false了。递归问题主要是找到递归出口和递归条件,递归条件应该是很简单的,只要四个方位求或关系就行了,返回一个布尔值作为结果。

下面找找递归出口以及边界(row表示行的索引,col表示列的索引):

第一个边界:if(row < 0 || col < 0 || row == board.length || col == board[0].length)肯定是false;

第二个边界:if(board[row][col] != word.charAt(index))对应的字符对不上,肯定也是返回false;

第三个边界(也是出口):index == word.length()递归的索引到达了给定字符串的末尾了,也就是说word中的所有字符都匹配了,返回的当然是true了。

代码:

主体部分:


递归部分:




原创粉丝点击