zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    基本计数方法
    每天工作4小时的程序员
    明星软件工程师的10种特质(转)
    IT高薪者所具备的人格魅力
    Unity_Shader开发_图形学基础(五)--------2016.1.9
    unity 架构设计的学习
    深入浅出聊优化:从Draw Calls到GC
    PG+mask替代透明Png(转)
    基于战斗重演的全校验---- 塔防大师PVP反外挂设计
    Unity项目开发准则
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/10341571.html
Copyright © 2011-2022 走看看