zoukankan      html  css  js  c++  java
  • 矩阵中查找单词

    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.

    private static final int[][] direction = {{1,0},{-1,0},{0,1},{0,-1}};
        
        public boolean exist(char[][] board,String word){
            if(word == null || word.length() == 0){
                return true;
            }
            if(board == null || board.length == 0 || board[0].length==0){
                return false;
            }
            boolean[][] hasVisited = new boolean[board.length][board[0].length];
            for(int r=0;r<board.length;r++){
                for(int c=0;c<board[0].length;c++){
                    if(backtracking(0,r,c,hasVisited,board,word)){
                        return true;
                    }
                }
            }
            return false;
        }
        
        private boolean backtracking(int curLen,int r,int c,boolean[][] visited,final char[][] board,final String word){
            if(curLen == word.length()){
                return true;
            }
            if(r<0||r>=board.length||c<0||c>=board[0].length || board[r][c]!=word.charAt(curLen)||visited[r][c]){
                return false;
            }
            visited[r][c] = true;
            
            for(int[] d :direction){
                if(backtracking(curLen+1, r, c, visited, board, word)){
                    return true;
                }
            }
            
            visited[r][c] = false;
            
            return false;
        }
  • 相关阅读:
    转inux Shell编程入门
    转CentOS — MySQL备份 Shell 脚本
    JAVA4种线程池的使用
    http://cyber-dojo.org/
    tomcat内存大小设置
    rails的数据库查询方法
    Java 微信公众号上传永久素材的方法
    微信回复图文消息
    plsql解决64位解决办法
    Ruby中使用patch HTTP方法
  • 原文地址:https://www.cnblogs.com/helloworldmybokeyuan/p/13446065.html
Copyright © 2011-2022 走看看