79. 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:

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

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

在矩阵中寻找字符串

java:
 1 class Solution {
 2     private int[][] direction = {{1,0} , {-1,0} , {0,1} , {0,-1}} ;
 3     private int n ;
 4     private int m ;
 5     public boolean exist(char[][] board, String word) {
 6         if (word == null || word.length() == 0){
 7             return true ;
 8         }
 9         if (board == null || board.length == 0 || board[0].length == 0){
10             return false ;
11         }
12         n = board.length ;
13         m = board[0].length ;
14         boolean[][] visit = new boolean[n][m] ;
15         for(int i = 0 ; i < n ; i++){
16             for(int j = 0 ; j < m ; j++){
17                 if (backtracking(0,board,word,visit,i,j)){
18                     return true ;
19                 }
20             }
21         }
22         return false ;
23     }
24     
25     public boolean backtracking(int curLen , char[][] board, String word, boolean[][] visit,int r, int c){
26         if (curLen == word.length()){
27             return true ;
28         }
29         if (r < 0 || r >= n || c < 0 || c >= m || visit[r][c] || board[r][c] != word.charAt(curLen)){
30             return false ;
31         }
32         visit[r][c] = true ;
33         for(int[] d : direction){
34             if (backtracking(curLen+1,board,word,visit,r+d[0],c+d[1])){
35                     return true ;
36                 }
37         }
38         visit[r][c] = false ;
39         return false ;
40     }
41 }

 

posted @ 2019-01-31 13:16  __Meng  阅读(154)  评论(0编辑  收藏  举报