首页 > 其他 > 详细

[LC] 79. Word Search

时间:2019-12-08 14:35:34      阅读:45      评论:0      收藏:0      [点我收藏+]

标签:cal   sed   ear   grid   ()   true   

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.

Time: O(M * N * 4^|Word|)
 1 class Solution {
 2     int row;
 3     int col;
 4     public boolean exist(char[][] board, String word) {
 5         row = board.length;
 6         col = board[0].length;
 7         boolean[][] visited = new boolean[row][col];
 8         for (int i = 0; i < row; i++) {
 9             for (int j = 0; j < col; j++) {
10                 if (helper(board, visited, word, i, j, 0)) {
11                     return true;
12                 }
13             }
14         }
15         return false;
16     }
17     
18     private boolean helper(char[][] board, boolean[][] visited, String word, int i, int j, int index) {
19         if (index == word.length()) {
20             return true;
21         }
22         if (i < 0 || i >= row || j < 0 || j >= col) {
23             return false;
24         }
25         if (word.charAt(index) == board[i][j] && !visited[i][j]) {
26             visited[i][j] = true;
27             boolean res = helper(board, visited, word, i + 1, j, index + 1) ||
28                 helper(board, visited, word, i - 1, j, index + 1) ||
29                 helper(board, visited, word, i, j + 1, index + 1) ||
30                 helper(board, visited, word, i, j - 1, index + 1);
31             // need to clean up visited
32             visited[i][j] = false;
33             return res;
34         }
35 
36         return false;
37     }
38 }

 

[LC] 79. Word Search

标签:cal   sed   ear   grid   ()   true   

原文:https://www.cnblogs.com/xuanlu/p/12005363.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 bubuko.com 版权所有 鲁ICP备09046678号-4
打开技术之扣,分享程序人生!
             

鲁公网安备 37021202000002号