Word Search

来源:互联网 发布:五金店做账用什么软件 编辑:程序博客网 时间:2024/06/05 17:20
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 =[["ABCE"],

["SFCS"],

["ADEE"]]

word = "ABCCED", -> returns true,

word = "SEE", -> returns true,

word = "ABCB", -> returns false.

题意是,给你一个二维字母的数组,可以上下左右走,查找是否某个单词是否存在。

同一位置的字母不可以被使用多次。

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(dfs(i,j,board,word,0))return true;}return false;}private boolean dfs(int i,int j,char[][] board, String word,int k){if(i<0||j<0||i>=board.length||j>=board[0].length)return false;if(board[i][j]==word.charAt(k)){char tmp=board[i][j];board[i][j]='#';//每个字符使用一次,使用后更改为某个特殊字符。如果不更改,[[aa]],"aaa"也返回true。if(k==word.length()-1)return true;else if(dfs(i+1,j,board,word,k+1)||dfs(i,j+1,board,word,k+1)||dfs(i-1,j,board,word,k+1)||dfs(i,j-1,board,word,k+1))return true;board[i][j]=tmp;}return false;}


0 0
原创粉丝点击