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.

Solution1:

这个题目基本上就是DFS喽。然后注意一下递归回溯的问题。我们可以建设一个boolean的数组来记录访问过的值。在return false之前,我们应该把之前置

过的标记位置回来. 时间复杂度: http://www1.mitbbs.ca/article_t1/JobHunting/32524193_32524299_2.html

time 复杂度是m*n*4^(k-1). 也就是m*n*4^k.
m X n is board size, k is word size.

recuision最深是k层,recursive部分空间复杂度应该是O(k) + O(m*n)(visit array)

 package Algorithms.dfs;

 public class Exist {
public boolean exist(char[][] board, String word) {
if (board == null || word == null
|| board.length == 0 || board[0].length == 0) {
return false;
} int rows = board.length;
int cols = board[0].length; boolean[][] visit = new boolean[rows][cols]; // i means the index.
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// dfs all the characters in the matrix
if (dfs(board, i, j, word, 0, visit)) {
return true;
}
}
} return false;
} public boolean dfs(char[][] board, int i, int j, String word, int wordIndex, boolean[][] visit) {
int rows = board.length;
int cols = board[0].length; int len = word.length();
if (wordIndex >= len) {
return true;
} // the index is out of bound.
if (i < 0 || i >= rows || j < 0 || j >= cols) {
return false;
} // the character is wrong.
if (word.charAt(wordIndex) != board[i][j]) {
return false;
} // 不要访问访问过的节点
if (visit[i][j] == true) {
return false;
} visit[i][j] = true; // 递归
// move down
if (dfs(board, i + 1, j, word, wordIndex + 1, visit)) {
return true;
} // move up
if (dfs(board, i - 1, j, word, wordIndex + 1, visit)) {
return true;
} // move right
if (dfs(board, i, j + 1, word, wordIndex + 1, visit)) {
return true;
} // move left
if (dfs(board, i, j - 1, word, wordIndex + 1, visit)) {
return true;
} // 回溯
visit[i][j] = false;
return false;
}
}

Solution2:

与解1是一样的,但我们可以省掉O(m*n)的空间复杂度。具体的作法是:在进入DFS后,把访问过的节点置为'#',访问完毕之后再置回来即可。

 /*
* Solution 2: 可以省掉一个visit的数组
* */
public boolean exist(char[][] board, String word) {
if (board == null || word == null
|| board.length == 0 || board[0].length == 0) {
return false;
} int rows = board.length;
int cols = board[0].length; // i means the index.
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// dfs all the characters in the matrix
if (dfs(board, i, j, word, 0)) {
return true;
}
}
} return false;
} public boolean dfs(char[][] board, int i, int j, String word, int wordIndex) {
int rows = board.length;
int cols = board[0].length; int len = word.length();
if (wordIndex >= len) {
return true;
} // the index is out of bound.
if (i < 0 || i >= rows || j < 0 || j >= cols) {
return false;
} // the character is wrong.
if (word.charAt(wordIndex) != board[i][j]) {
return false;
} // mark it to be '#', so we will not revisit this.
board[i][j] = '#'; // 递归
// move down
if (dfs(board, i + 1, j, word, wordIndex + 1)) {
return true;
} // move up
if (dfs(board, i - 1, j, word, wordIndex + 1)) {
return true;
} // move right
if (dfs(board, i, j + 1, word, wordIndex + 1)) {
return true;
} // move left
if (dfs(board, i, j - 1, word, wordIndex + 1)) {
return true;
} // 回溯
board[i][j] = word.charAt(wordIndex);
return false;
}

December 16th, 2014 重写,简洁一点点,11分钟1次AC.

其实这里的回溯有一个点要注意,就是当dfs返回true时,我们并没有回溯。原因是这时整个dfs就结束了,我们也就不需要再回溯。否则一般的递归/回溯结构

这里是需要先回溯再返回的。

 public class Solution {
public boolean exist(char[][] board, String word) {
if (board == null || board.length == 0 || board[0].length == 0) {
return false;
} int rows = board.length;
int cols = board[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// Check if there is a word begin from i,j.
if (dfs(board, word, i, j, 0)) {
return true;
}
}
} return false;
} public boolean dfs(char[][] board, String word, int i, int j, int index) {
int len = word.length();
if (index >= len) {
return true;
} // Check the input parameter.
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) {
return false;
} // If the current character is right.
if (word.charAt(index) != board[i][j]) {
return false;
} char tmp = board[i][j];
board[i][j] = '#'; // recursion.
if (dfs(board, word, i + 1, j, index + 1)
|| dfs(board, word, i - 1, j, index + 1)
|| dfs(board, word, i, j + 1, index + 1)
|| dfs(board, word, i, j - 1, index + 1)
) {
return true;
} // backtrace.
board[i][j] = tmp;
return false;
}
}

虽然前面的方法可以AC,但考虑到最好不要更改入参的值,所以在return true前,我们还是加一个回溯代码。

 public class Solution {
public boolean exist(char[][] board, String word) {
if (board == null || board.length == 0 || board[0].length == 0) {
return false;
} int rows = board.length;
int cols = board[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// Check if there is a word begin from i,j.
if (dfs(board, word, i, j, 0)) {
return true;
}
}
} return false;
} public boolean dfs(char[][] board, String word, int i, int j, int index) {
int len = word.length();
if (index >= len) {
return true;
} // Check the input parameter.
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) {
return false;
} // If the current character is right.
if (word.charAt(index) != board[i][j]) {
return false;
} char tmp = board[i][j];
board[i][j] = '#'; boolean ret = dfs(board, word, i + 1, j, index + 1)
|| dfs(board, word, i - 1, j, index + 1)
|| dfs(board, word, i, j + 1, index + 1)
|| dfs(board, word, i, j - 1, index + 1); // backtrace.
board[i][j] = tmp;
return ret;
}
}

GitHub代码:

exist.java

LeetCode: Word Search 解题报告的更多相关文章

  1. 【LeetCode】79. Word Search 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 回溯法 日期 题目地址:https://leetco ...

  2. LeetCode: Combination Sum 解题报告

    Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...

  3. LeetCode & Binary Search 解题模版

    LeetCode & Binary Search 解题模版 In computer science, binary search, also known as half-interval se ...

  4. [LeetCode] Word Search II 词语搜索之二

    Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...

  5. [LeetCode] Word Search 词语搜索

    Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from l ...

  6. 【LeetCode】Permutations 解题报告

    全排列问题.经常使用的排列生成算法有序数法.字典序法.换位法(Johnson(Johnson-Trotter).轮转法以及Shift cursor cursor* (Gao & Wang)法. ...

  7. LeetCode - Course Schedule 解题报告

    以前从来没有写过解题报告,只是看到大肥羊河delta写过不少.最近想把写博客的节奏给带起来,所以就挑一个比较容易的题目练练手. 原题链接 https://leetcode.com/problems/c ...

  8. Leetcode: word search

    July 6, 2015 Problem statement: Word Search Given a 2D board and a word, find if the word exists in ...

  9. LeetCode: Sort Colors 解题报告

    Sort ColorsGiven an array with n objects colored red, white or blue, sort them so that objects of th ...

随机推荐

  1. Tomcat跨二级域配置

    内容转自:http://blog.csdn.net/luka2008/article/details/38385703/,请直接看原文,不过这篇“原文”也是转的... 1,Tomcat下 代码: im ...

  2. webview使用遇到 It is possible that this object was over-released, or is in the process of deallocation错误的解决办法

    使用wekwebview时,push后,再pop返回,报错了: Cannot form weak reference to instance (xxxx) of class xxxx. It is p ...

  3. iOS AppIcon尺寸和上传ITunes构建版本尺寸和iPhone屏幕尺寸

    避免忘记. 记录一下 App Icon: 29X2940X4058X5876X7687X8780X80120X120152X152167X167180X180 ITunes构建版本: 1242 x 2 ...

  4. java测试Unicode编码以及数组的运用(初学篇)

    /*第二章第四小题*/ /* * (1)编写一个应用程序,给出汉字“你” ,“我”,“他”在Unicode 表中的位置 * (2)编写一个java应用程序,输出全部的希腊字母 */ public cl ...

  5. Foundations of Machine Learning: Rademacher complexity and VC-Dimension(1)

    Foundations of Machine Learning: Rademacher complexity and VC-Dimension(1) 前面两篇文章中,我们在给出PAC-learnabl ...

  6. java MessageFormat.format

    sql 语句中格式化,如果加入{}占位符,要替代的是整形变量,而恰好这个整形变量的位数超过4位, MessageFormat.format 会在这个整形变量中默认每隔三位加一个逗号,类似这样:1000 ...

  7. JVM性能监控

    有时候我们会碰到下面这些问题: OutOfMemoryError,内存不足 内存泄露 线程死锁 锁争用(Lock Contention) Java进程消耗CPU过高 这些问题在日常开发中可能被很多人忽 ...

  8. android检测网络连接状态示例讲解

    网络的时候,并不是每次都能连接到网络,因此在程序启动中需要对网络的状态进行判断,如果没有网络则提醒用户进行设置   Android连接首先,要判断网络状态,需要有相应的权限,下面为权限代码(Andro ...

  9. Facade - 外观模式

    1. 概述 外观模式,我们通过外观的包装,使应用程序只能看到外观对象,而不会看到具体的细节对象,这样无疑会降低应用程序的复杂度,并且提高了程序的可维护性.例子1:一个电源总开关可以控制四盏灯.一个风扇 ...

  10. 如何恢复 Linux删除的文件

    原理及普通文件的恢复 要想恢复误删除的文件,必须清楚数据在磁盘上究竟是如何存储的,以及如何定位并恢复数据.本文从数据恢复的角度,着重介绍了 ext2 文件系统中使用的一些基本概念和重要数据结构,并通过 ...