word search

来源:互联网 发布:熹妃传刷元宝软件 编辑:程序博客网 时间:2024/06/06 05:25

Given a 2D board and a word, find if the word exists in thegrid.

The word can be constructed from letters of sequentially adjacentcell, where "adjacent" cells are those horizontally or verticallyneighboring. The same letter cell may not be used more thanonce.

For example,
Given board =

[  ["ABCE"],  ["SFCS"],  ["ADEE"]]
word "ABCCED",-> returns true,
word "SEE",-> returns true,
word "ABCB",-> returns false.

中心思想:
1. 典型的递归。如果查找的index超过单词长度,则返回true。
2.记录上一次搜索的行列标号,然后在其上下左右四个方位搜索。为了记录已搜索位置,将搜索过的位置标记为'#'。如果搜索失败,重置当前位。

有个地方值得注意:在index+1的地方,我使用index++。我猜原因是在调用函数的时候,index还没有加1,直到调用结束才++。

public class Solution {
    public booleanexist(char[][] board, String word) {
       // Start typing your Java solution below
       // DO NOT write main() function
       if (word == null) {
           returnfalse;
       }
       for (int row = 0; row <board.length; row++) {
           for (intcol = 0; col < board[0].length; col++) {
              if (board[row][col] ==word.charAt(0)) {
                 board[row][col] = '#';
                 if (helper(board, word, 1, row, col)) {
                     returntrue;
                 }
                 board[row][col] = word.charAt(0);
              }
           }
       }
       return false;
    }
    
    boolean helper(char[][]board, String word, int index, int lastRow, int lastCol) {
       if (index > (word.length()-1) ){
           returntrue;
       }
       char ch = word.charAt(index);
       
       // row-1, col
       int upRow = Math.max(0, lastRow-1);
       if (board[upRow][lastCol] == ch) {
          board[upRow][lastCol] = '#';
           if(helper(board, word, index+1, upRow, lastCol)) {
              return true;
           }
          board[upRow][lastCol] = ch;
       }
       // row+1, col
       int lowRow = Math.min(board.length-1,lastRow+1);
       if (board[lowRow][lastCol] == ch) {
          board[lowRow][lastCol] = '#';
           if (helper(board, word, index+1, lowRow, lastCol)) {
              return true;
           }
          board[lowRow][lastCol] = ch;
       }
       // row, col-1
       int leftCol = Math.max(0, lastCol-1);
       if (board[lastRow][leftCol] == ch) {
          board[lastRow][leftCol] = '#';
           if(helper(board, word, index+1, lastRow, leftCol)) {
              return true;
           }
          board[lastRow][leftCol] = ch;
       }
       // row, col+1
       int rightCol = Math.min(board[0].length-1,lastCol+1);
       if (board[lastRow][rightCol] == ch) {
          board[lastRow][rightCol] = '#';
           if (helper(board, word, index+1, lastRow, rightCol)) {
              return true;
           }
          board[lastRow][rightCol] = ch;
       }
       return false;
    }
    
}
0 0
原创粉丝点击