leetCode练习(79)

来源:互联网 发布:好看的手机壁纸软件 编辑:程序博客网 时间:2024/05/19 04:53

题目:Word Search

难度:medium

问题描述:

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.

解题思路:走迷宫一样,问有没有一条路径等于word。对每一个值为word[0]的节点使用DFS,若有满足的路径即可返回true。使用一个Boolean[][] count记录是否被走过。

另一个思路是使用BFS,但BFS同时有多条路径在走,需要大量count,得不偿失。

DFS代码如下:

public class m_79_WordSearch {public boolean exist(char[][] board, String word) {          for(int i=0;i<board.length;i++){       for(int j=0;j<board[0].length;j++){       if(board[i][j]==word.charAt(0)){       if(DFS(board,i,j,word,new boolean[board.length][board[0].length])){           return true;           }       }       }       }       return false;    }private boolean DFS(char[][] board, int x,int y,String word, boolean[][] count) {if(board[x][y]!=word.charAt(0)){return false;}if(word.length()==1){return true;}count[x][y]=true;if(x>0&&!count[x-1][y]){if(DFS(board,x-1,y,word.substring(1),count)){return true;}}if(x<board.length-1&&!count[x+1][y]){if(DFS(board,x+1,y,word.substring(1),count)){return true;}}if(y>0&&!count[x][y-1]){if(DFS(board,x,y-1,word.substring(1),count)){return true;}}if(y<board[0].length-1&&!count[x][y+1]){if(DFS(board,x,y+1,word.substring(1),count)){return true;}}count[x][y]=false;return false;}}

0 0
原创粉丝点击