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.

    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.

    本题重点在于体会回溯的方法,需要注意的是每次访问的时候需要加一个boolean值来确定是否访问过,代码如下:

    public class Solution {
        public boolean exist(char[][] board, String word) {
            if(board==null||board.length==0||board[0].length==0) return false;
            if(word.length()==0) return true;
            int m = board.length;
            int n= board[0].length;
            for(int i=0;i<m;i++){
                for(int j=0;j<n;j++){
                    boolean[][] tested = new boolean[m][n];
                    if(helper(board,word,tested,i,j,0)){
                        return true;
                    }
                }
            }
            return false;
        }
        public boolean helper(char[][] board,String word,boolean[][] tested,int row,int col,int cur){
            if(cur==word.length()) return true;
            if(row<0||row>=board.length||col<0||col>=board[0].length||board[row][col]!=word.charAt(cur)||tested[row][col]==true) return false;
            tested[row][col] = true;
            boolean exist=helper(board,word,tested,row+1,col,cur+1)||helper(board,word,tested,row,col+1,cur+1)||helper(board,word,tested,row-1,col,cur+1)||helper(board,word,tested,row,col-1,cur+1);
            tested[row][col]=false;
            return exist;
        }
    }

     本题可以不用创建boolean数组,只要让那个位置的值异或256。

  • 相关阅读:
    协议分析 - DHCP协议解码详解
    在SqlServer2000的视图中小心使用*符号
    sql 将 varchar 值转换为数据类型为 int 的列时发生语法错误 的解决办法
    LECCO SQL Expert工具之优化sql语句
    css+js简单应用
    对任何一天是星期几算法的实现
    asp.net ajax 1.0 出现"sys"未定义解决方法
    js日历脚本
    在ASP.NET中重写URL
    在ASP.NET中重写URL (续篇)
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6380539.html
Copyright © 2011-2022 走看看