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;        
        }
        
    }
     

     

  • 相关阅读:
    iOS UITextField 设置内边距
    在网页中嵌入任意字体的解决方案
    基数等比,确定进制
    改善CSS编码的5个在线幻灯片教程
    head区的代码详解
    一个简单的、循序渐进的CSS幻灯片教程
    功能强大易用的Web视频播放器——Flowplayer(使用方法及演示)
    CSS:区分IE版本的三个方法
    CSS书写标准及最佳实践
    Sliding Photograph Galleries
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/5967061.html
Copyright © 2011-2022 走看看