【leetcode】Array——word search(79)
来源:互联网 发布:js 自定义属性 data 编辑:程序博客网 时间:2024/05/16 23:53
题目:
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.
解题:
1. 获取多维数组的长度//遍历多维数组(支持非方正)
for(int i =0;i<array.length;i++){
for(int j=0;j<array[i].lengh;j++){
for(int k=0;k<array[i][j].length;k++){
syso(array[i][j][k]);
}
}
}
2. 解题思路
- 遍历数组时,匹配string的第一个char,作为入口
- 开始递归(深度优先),找到完全匹配,返回true
- 匹配不上时,要消除标记位,恢复现场
public boolean exist(char[][] board, String word) { char c0 = word.charAt(0); boolean [][]flag = new boolean[board.length][board[0].length]; for(int i=0;i<board.length;i++){ for(int j=0;j<board[0].length;j++){ char c = board[i][j]; if(c==c0){ if(has_next(board,flag,word,1,i,j)) return true; flag[i][j]=false; } } } return false;}private boolean has_next(char[][] board,boolean [][]flag,String word,int word_index,int i,int j){ int hang = board.length; int lie = board[0].length;flag[i][j]=true;if(word_index>=word.length())return true;char c1 = word.charAt(word_index);if(i-1>=0&&c1==board[i-1][j]&&flag[i-1][j]!=true){//upif(has_next(board, flag, word,word_index+1, i-1, j))return true;flag[i-1][j]=false;}if(j-1>=0&&c1==board[i][j-1]&&flag[i][j-1]!=true){//leftif(has_next(board, flag, word,word_index+1, i, j-1))return true;flag[i][j-1]=false;}if(i+1<hang&&c1==board[i+1][j]&&flag[i+1][j]!=true){//downif(has_next(board, flag, word,word_index+1, i+1, j))return true;flag[i+1][j]=false;}if(j+1<lie&&c1==board[i][j+1]&&flag[i][j+1]!=true){//rightif(has_next(board, flag, word,word_index+1, i, j+1))return true;flag[i][j+1]=false;}return false;}
3. tips
对于标记位的实现,一开始是开辟新的内存空间,flag[][]存标记,改进board[i][j]^=256,恢复也是board[i][j]^=256
或者用’#’等其他的字符替换,不过这个不一定靠谱。
0 0
- 【leetcode】Array——word search(79)
- [LeetCode]—Word Search
- LeetCode刷题【Array】 Word Search
- leetcode.array--79. Word Search
- LeetCode —— Word Search
- leetcode——Word Search
- Leetcode 79 Word Search
- LeetCode 79: Word Search
- [leetcode 79] Word Search
- [LeetCode 79]Word Search
- leetcode || 79、Word Search
- [leetCode]79(Word Search)
- leetcode-79 Word Search
- Leetcode #79 Word Search
- Leetcode #79 Word Search
- LeetCode(79) Word Search
- leetcode 79: Word Search
- 【leetcode】【79】Word Search
- LeetCode 237. Delete Node in a Linked List
- App上线流程
- Android开发学习之路--Broadcast Receiver之初体验
- 27. Remove Element LeetCode
- PECL 和 PEAR 有什么区别?
- 【leetcode】Array——word search(79)
- 关于编程语言中的显式\隐式初始化
- leetcode191题 题解 翻译 C语言版 Python版
- 面试笔试杂项积累-leetcode 211-215
- 26. Remove Duplicates from Sorted Array LeetCode
- 【leetcode】Array——Unique Paths(62)
- django学习之 pdf报表(表格)生成
- Java—设计模式(工厂模式)
- java常见问题