Leetcode: Word Search
来源:互联网 发布:家用粉碎机知乎 编辑:程序博客网 时间:2024/06/05 18:40
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
.Search for each element in given board and its neighbors to see whether they can consist to the word. Use a new boolean board to represent whether that element is already used. And each time a new search begins, the boolean board should be false for each element. Time complexity O(m^2 * n ^2).
public class Solution { public boolean exist(char[][] board, String word) { if (board == null || board.length == 0 || board[0].length == 0) { return false; } if (word == null || word.length() == 0) { return true; } ArrayList<Integer> x = new ArrayList<Integer>(); ArrayList<Integer> y = new ArrayList<Integer>(); for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (board[i][j] == word.charAt(0)) { x.add(i); y.add(j); } } } boolean[][] visited = new boolean[board.length][board[0].length]; for (int i = 0; i < x.size(); i++) { if (helperExist(board, x.get(i), y.get(i), word, 0, visited)) { return true; } } return false; } private boolean helperExist(char[][] board, int x, int y, String word, int pos, boolean[][] visited) { if (pos == word.length()) { return true; } if (x < 0 || x >= board.length || y < 0 || y >= board[0].length || visited[x][y] == true || board[x][y] != word.charAt(pos)) { return false; } visited[x][y] = true; boolean res = helperExist(board, x - 1, y, word, pos + 1, visited) || helperExist(board, x + 1, y, word, pos + 1, visited) || helperExist(board, x, y - 1, word, pos + 1, visited) || helperExist(board, x, y + 1, word, pos + 1, visited); visited[x][y] = false; return res; }}
0 0
- LeetCode: Word Search
- [Leetcode] Word Search
- LeetCode : Word Search
- Leetcode: Word Search
- [LeetCode] Word Search
- leetcode 56: Word Search
- Leetcode 79 Word Search
- [leetcode ] word search
- [Leetcode] Word Search
- [LeetCode]Word Search
- Leetcode Word Search
- [leetcode]word search
- [leetcode] Word Search
- LeetCode-Word Search
- [LeetCode] Word Search
- LeetCode - Word Search
- leetcode word search
- LeetCode:Word Search
- 39级台阶
- 【jstl学习】一
- Visual Basic.net 检测网络连接状态的两种方法
- 快乐SDA股第三届阿萨德的功夫
- 数据可视化制作工具推荐
- Leetcode: Word Search
- Visual Basic.Net 代理服务器的实例
- 北美+德国18所名校数据科学课程汇总
- 渗透思路整理
- 腾讯CDC:用户流失原因调研四步经
- 采访德国支付方式—微支付GmbH
- 用数据追女神:追女生如同创业
- 大数据只做三件事,对用户的理解、对信息的理解、对关系的理解
- 数据分析基本思路及手法