首页 > 代码库 > 【LeetCode】Word Search 解题报告
【LeetCode】Word Search 解题报告
【题目】
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
.【解析】
DFS;回溯;递归。
public class Solution { char[][] board; int m, n; public boolean exist(char[][] board, String word) { if (board == null || word == null) return false; if (("").equals(word)) return true; this.board = board; m = board.length; n = board[0].length; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == word.charAt(0)) { char tmp = board[i][j]; board[i][j] = '#'; if (dfs(i, j, word.substring(1))) return true; board[i][j] = tmp; } } } return false; } public boolean dfs(int i, int j, String word) { if (("").equals(word)) return true; char tar = word.charAt(0); String left = word.substring(1); if (i > 0 && board[i - 1][j] == tar) { board[i - 1][j] = '#'; if (dfs(i - 1, j, left)) return true; board[i - 1][j] = tar; } if (j > 0 && board[i][j - 1] == tar) { board[i][j - 1] = '#'; if (dfs(i, j - 1,left)) return true; board[i][j - 1] = tar; } if (i < m - 1 && board[i + 1][j] == tar) { board[i + 1][j] = '#'; if (dfs(i + 1, j, left)) return true; board[i + 1][j] = tar; } if (j < n - 1 && board[i][j + 1] == tar) { board[i][j + 1] = '#'; if (dfs(i, j + 1, left)) return true; board[i][j + 1] = tar; } return false; } }
【LeetCode】Word Search 解题报告
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。