• leetcode——79.单词搜索


    这道题自己完成的,不难。

    回溯。

    public boolean exist(char[][] board, String word) {
            int m = board.length;
            int n = board[0].length;
            int wordLength = word.length();
            if(word.length()>m*n){
                return false;
            }
            boolean[][] b = new boolean[m][n];
            for(int i = 0;i<m;i++){
                for(int j = 0;j<n;j++){
                    if(board[i][j] == word.charAt(0)){
                        b[i][j] = true;
                        if(find(board,b,word,i,j,1,m,n,wordLength)){
                            return true;
                        }
                        b[i][j] = false;
                    }
                }
            }
            return false;
        }
    
        private boolean find(char[][] board, boolean[][] b, String word, int i, int j, int k, int m, int n, int wordLength) {
            if(k == wordLength){
                return true;
            }
            if(i+1<m){
                if(!b[i+1][j] && board[i+1][j] == word.charAt(k)){
                    b[i+1][j] = true;
                    if(find(board, b, word, i+1, j, k+1, m, n, wordLength)){
                        return true;
                    }
                    b[i+1][j] = false;
                }
            }
            if(i-1>=0){
                if(!b[i-1][j] && board[i-1][j] == word.charAt(k)){
                    b[i-1][j] = true;
                    if(find(board, b, word, i-1, j, k+1, m, n, wordLength)){
                        return true;
                    }
                    b[i-1][j] = false;
                }
            }
            if(j+1<n){
                if(!b[i][j+1] && board[i][j+1] == word.charAt(k)){
                    b[i][j+1] = true;
                    if(find(board, b, word, i, j+1, k+1, m, n, wordLength)){
                        return true;
                    }
                    b[i][j+1] = false;
                }
            }
            if(j-1>=0){
                if(!b[i][j-1] && board[i][j-1] == word.charAt(k)){
                    b[i][j-1] = true;
                    if(find(board, b, word, i, j-1, k+1, m, n, wordLength)){
                        return true;
                    }
                    b[i][j-1] = false;
                }
            }
            return false;
        }

    待优化。

     ——2020.6.30

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    漫谈五种IO模型
    jvm调优-命令大全(jps jstat jmap jhat jstack jinfo)
    Intellij IDEA 插件开发秘籍
    二进制
    java程序员必知的 8大排序
    Redis常见问题
    BitMap位图
    编程思想
    Final修饰的字段是否可以通过反射设置值
    ORACLE 11g ORA-20000: Unable to analyze TABLE "AA"."CMP3$87651", insufficient privileges or does not exist
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/13212525.html
Copyright © 2020-2023  润新知