zoukankan      html  css  js  c++  java
  • leetcode------Word Search

    标题: Word Search
    通过率: 20.0%
    难度: 中等

    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.

    需要尝试从每一个位置起开始遍历,每次向四个方向开始遍历,如果四个方向都不满足时要将走过的路径回复,边界问题看代码:

    用一个index记录查了多少个了。

    迭代算法依然没有知道突破口:

     1 public class Solution {
     2     private int m,n;
     3     public boolean exist(char[][] board, String word) {
     4         m=board.length;
     5         n=board[0].length;
     6         boolean [][] visted=new boolean[m][n];
     7         for(int i=0;i<m;i++)
     8         for(int j=0;j<n;j++){
     9             if(dfs(board,word,0,i,j,visted))
    10                 return true;
    11         }
    12         return false;
    13     }
    14     public boolean dfs(char[][] board, String word,int index,int startx,int starty,boolean [][] visted){
    15         if(index==word.length())return true;
    16         if(startx<0||startx>=m||starty<0||starty>=n)return false;
    17         if(visted[startx][starty])return false;
    18         if(board[startx][starty]!=word.charAt(index))return false;
    19         visted[startx][starty]=true;
    20         boolean res=dfs(board,word,index+1,startx+1,starty,visted)||dfs(board,word,index+1,startx-1,starty,visted)||dfs(board,word,index+1,startx,starty+1,visted)||dfs(board,word,index+1,startx,starty-1,visted);
    21         visted[startx][starty]=false;
    22         return res;
    23     }
    24 }
  • 相关阅读:
    新年新气象,用新年的喜庆来迎接的生活
    vs2005中如何发布网站及打包web项目生成安装文件
    完整打印页面控件的解决方案
    vi使用体会
    向ATL DLL中传递C++对象
    CentOS 5.3配置软件源以及CVS服务器
    堆上多维数组的内存管理
    物理坐标与逻辑坐标
    好友列表的实现
    在STL中处理对象指针
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4349936.html
Copyright © 2011-2022 走看看