首页 > 代码库 > [LeetCode]Word Search
[LeetCode]Word Search
题目:Word Search
判断某一单词是否在一个字母数组中用一条折线连起来。
[ [‘A‘,‘B‘,‘C‘,‘E‘], [‘S‘,‘F‘,‘C‘,‘S‘], [‘A‘,‘D‘,‘E‘,‘E‘] ]
word = "ABCCED"
, -> returns true
,
坐标序列如下:00,01,02,12,22,21
思路:
递归查找单词当前字母对应数组的坐标的前后左右,看能都匹配。
package com.example.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. * @author FuPing * */ public class Exist { /** *@param i,j 当前元素的坐标 *@param word 查找单词 *@param k 查找单词的字母的下标 *@param visit 所有已访问过元素的标记 */ private boolean check(char[][] board,int i,int j,String word,int k,int[][] visit){ if(k >= word.length())return true; if(i > 0 && board[i-1][j] == word.charAt(k) && visit[i-1][j] == 0){//查找当前字母的上边 visit[i-1][j] = 1; if(check(board,i-1,j,word,k+1,visit))return true; visit[i-1][j] = 0; } if(j < board[0].length - 1 && board[i][j+1] == word.charAt(k) && visit[i][j+1] == 0){//查找当前字母的右边 visit[i][j+1] = 1; if(check(board,i,j+1,word,k+1,visit))return true; visit[i][j+1] = 0; } if(i < board.length - 1 && board[i+1][j] == word.charAt(k) && visit[i+1][j] == 0){//查找当前字母的下边 visit[i+1][j] = 1; if(check(board,i+1,j,word,k+1,visit))return true; visit[i+1][j] = 0; } if(j > 0 && board[i][j-1] == word.charAt(k) && visit[i][j-1] == 0){//查找当前字母的左边 visit[i][j-1] = 1; if(check(board,i,j-1,word,k+1,visit))return true; visit[i][j-1] = 0; } return false; } public boolean exist(char[][] board, String word) { int[][] visit = new int[board.length][board[0].length]; for(int i = 0;i < board.length;i++){ for(int j = 0;j < board[i].length;j++){ if(board[i][j] == word.charAt(0)){//找到与首字母相同的地方 visit[i][j] = 1; if(check(board, i, j, word, 1, visit))return true; visit[i][j] = 0; } } } return false; } public static void main(String[] args) { // TODO Auto-generated method stub char[][] board = {{‘a‘,‘a‘,‘a‘,‘a‘}, {‘a‘,‘a‘,‘a‘,‘a‘}, {‘a‘,‘a‘,‘a‘,‘a‘}, {‘a‘,‘a‘,‘a‘,‘a‘}}; System.out.println(new Exist().exist(board, "aaaaaaaaaaaaaaaaaaa")); } }
[LeetCode]Word Search
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。