zoukankan      html  css  js  c++  java
  • leetcode -- 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.

    [解题思路]

    DFS 深度优先搜索

     1 public boolean exist(char[][] board, String word) {
     2         // Start typing your Java solution below
     3         // DO NOT write main() function
     4         int wLen = word.length();
     5         if(wLen == 0){
     6             return true;
     7         }
     8         
     9         int row = board.length;
    10         if(row == 0){
    11             return false;
    12         }
    13         int col = board[0].length;
    14         for(int i = 0; i < row; i++){
    15             for(int j = 0; j < col; j++){
    16                 if(board[i][j] == word.charAt(0)){
    17                     boolean found = find(board, word, new boolean[row][col], 0, i, j);
    18                     if(found){
    19                         return found;
    20                     }
    21                 }
    22             }
    23         }
    24         return false;
    25         
    26     }
    27     
    28     public boolean find(char[][] board, String word, boolean[][] visited, int depth,
    29             int i, int j){
    30             if(depth == word.length()){
    31                 return true;
    32             }    
    33                 
    34             if(i < 0 || i >= board.length || j < 0 || j >= board[0].length 
    35                 || (visited[i][j] == true) || word.charAt(depth) != board[i][j]){
    36                 return false;
    37             }
    38             
    39             visited[i][j] = true;
    40             
    41             // top, down, left, right
    42             return find(board, word, visited, depth + 1, i - 1, j) ||
    43                 find(board, word, visited, depth + 1, i + 1, j) ||
    44                 find(board, word, visited, depth + 1, i, j - 1) ||
    45                 find(board, word, visited, depth + 1, i, j + 1);
    46     }

    网上关于深度优先搜索的总结帖:

    http://cuijing.org/interview/leetcode/summary-of-dfs-and-bfs-in-leetcode.html

    http://leetcodenotes.wordpress.com/2013/08/24/leetcode-word-search-%E4%BA%8C%E7%BB%B4%E7%9F%A9%E9%98%B5%E6%89%BE%E9%87%8C%E9%9D%A2%E7%9A%84%E5%8D%95%E8%AF%8D/

  • 相关阅读:
    损失函数及其梯度
    激活函数及其梯度
    梯度下降简介
    误差计算
    输出方式
    全连接层
    测试(张量)- 实战
    数据加载
    高阶操作
    java网络基础知识的简述
  • 原文地址:https://www.cnblogs.com/feiling/p/3292649.html
Copyright © 2011-2022 走看看