leetcode_Word Search

来源:互联网 发布:淘宝怎么避免同款 编辑:程序博客网 时间:2024/06/08 17:24

题目描述:
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.
——————————————————————————————
由于每个数只能访问不超过一次,就想找一条只能横或者竖的线段,自然而然想到用DFS。
1.DFS要注意如何标记已访问的和未访问的,用“#”赋值已访问的,若发现已经不可行了,将原来的数还原。
2.每次可访问的是 上下左右未越界且未访问。

public class Solution3 {     public boolean exist(char[][] board, String word) {         for(int i=0;i<board.length;i++){             for(int j=0;j<board[i].length;j++){                 if(exist(board,i,j,word,0))return true;             }         }       return false;     }     public boolean exist(char[][] board,int x,int y,String word,int index){         if(index>=word.length())             return true;         if(x<0||x>=board.length||y<0||y>=board[0].length)return false;         if(board[x][y]==word.charAt(index)){             index++;             char c=board[x][y];             board[x][y]='#';             boolean tmp=(exist(board, x-1,y,word,index)||exist(board, x+1, y, word, index)||                     exist(board, x, y-1, word, index)||exist(board, x, y+1, word, index));            board[x][y]=c;            return tmp;         }         return false;     }     public static void main(String[] args){         char[][] board={{'a','a'}};         String word="aaa";         System.out.println(new Solution3().exist(board, word));     }}

(自己的代码实在冗余了,以上代码参考过leetcode discussion simple solution)

0 0