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

    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 = 

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

    word = "ABCCED", -> returns true,
    word = "SEE", -> returns true,
    word = "ABCB", -> returns false.

    给定一个矩阵和一个单词,查找该单词是否存在于矩阵中,只能垂直或者水平移动。同一个字母只能用一次。

    利用回溯,以及一个记录路径的数组,可以得到很好的结果。
    public class Solution {
        int[][] res ;
        char[] Word;
        public boolean exist(char[][] board, String word) {
            int row = board.length,len = word.length();
            if( len == 0 )
                return true;
            int col = board[0].length;
            if( len > row*col || row == 0 )
                return false;
            Word = word.toCharArray();
            res = new int[row][col];
    
            for( int i = 0;i<row;i++){
                for( int j = 0;j<col;j++){
                    if( Word[0] == board[i][j] ){
                        if(    start(board,i,j,1)    )
                            return true;
                     }
                }
            }
            return false;
    
        }
        public boolean start(char[][] board,int i,int j,int num){
            if( num == Word.length )
                return true;
            res[i][j] = -1;
            char ch = Word[num];
            if( j-1 >= 0 && res[i][j-1] != -1 && ch == board[i][j-1])
                if( start(board,i,j-1,num+1) )
                    return true;
            if( j+1 < board[0].length && res[i][j+1] != -1 && ch == board[i][j+1])
                if( start(board,i,j+1,num+1) )
                    return true;
            if( i-1 >= 0 && res[i-1][j] != -1 && ch == board[i-1][j] )
                if( start(board,i-1,j,num+1) )
                    return true;
            if( i+1 < board.length && res[i+1][j] != -1 && ch == board[i+1][j] )
                if( start(board,i+1,j,num+1))
                    return true;
            res[i][j] = 0;
            return false;        
        }
        
    }
     

     

  • 相关阅读:
    第07节-开源蓝牙协议BTStack框架代码阅读(上)
    第06节-开源蓝牙协议BTStack框架分析
    第05节-BLE协议物理层(PHY)
    第04节-BLE协议抓包演示
    第03节-BLE协议各层数据格式概述
    【重点声明】此系列仅用于工作和学习,禁止用于非法攻击。一切遵守《网络安全法》
    海外信息安全资源
    从浏览器攻击思考入门的问题。
    攻击载荷免杀技术
    聊聊NTLM认证协议
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/5967061.html
Copyright © 2011-2022 走看看