首页 > 代码库 > leetcode 79 Word Search ----- java
leetcode 79 Word Search ----- java
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
.
给定一个矩阵和一个单词,查找该单词是否存在于矩阵中,只能垂直或者水平移动。同一个字母只能用一次。
利用回溯,以及一个记录路径的数组,可以得到很好的结果。
public class Solution { int[][] res ; char[] Word; public boolean exist(char[][] board, String word) { int row = board.length,len = word.length(); if( len == 0 ) return true; int col = board[0].length; if( len > row*col || row == 0 ) return false; Word = word.toCharArray(); res = new int[row][col]; for( int i = 0;i<row;i++){ for( int j = 0;j<col;j++){ if( Word[0] == board[i][j] ){ if( start(board,i,j,1) ) return true; } } } return false; } public boolean start(char[][] board,int i,int j,int num){ if( num == Word.length ) return true; res[i][j] = -1; char ch = Word[num]; if( j-1 >= 0 && res[i][j-1] != -1 && ch == board[i][j-1]) if( start(board,i,j-1,num+1) ) return true; if( j+1 < board[0].length && res[i][j+1] != -1 && ch == board[i][j+1]) if( start(board,i,j+1,num+1) ) return true; if( i-1 >= 0 && res[i-1][j] != -1 && ch == board[i-1][j] ) if( start(board,i-1,j,num+1) ) return true; if( i+1 < board.length && res[i+1][j] != -1 && ch == board[i+1][j] ) if( start(board,i+1,j,num+1)) return true; res[i][j] = 0; return false; } }
leetcode 79 Word Search ----- java
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。