Word Search
来源:互联网 发布:自动编程软件 编辑:程序博客网 时间:2024/06/11 22:19
Word Search
Given a 2D board and a word, find if the word exists in the grid.
题意很简单,给你一个二维字母的数组,可以上下左右走,查找是否某个单词是否存在。同一位置的字母不可以被使用多次。
代码
public class Solution { static boolean[][] visited; public boolean exist(char[][] board, String word) { visited = new boolean[board.length][board[0].length]; for(int i = 0; i < board.length; i++){ for(int j = 0; j < board[i].length; j++){ if((word.charAt(0) == board[i][j]) && search(board, word, i, j, 0)){ return true; } } } return false; } private boolean search(char[][]board, String word, int i, int j, int index){ if(index == word.length()){ //当相等时表示word字符串已经全部查找完,全部找到返回true return true; } if(i >= board.length || i < 0 || j >= board[i].length || j < 0 || board[i][j] != word.charAt(index) || visited[i][j]){ return false; } visited[i][j] = true; if(search(board, word, i-1, j, index+1) || //有一个能找到即为真 search(board, word, i+1, j, index+1) || search(board, word, i, j-1, index+1) || search(board, word, i, j+1, index+1)){ return true; } visited[i][j] = false; return false; }}
0 0
- Word Search
- Word Search
- word search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- Word Search
- EventBus的初级使用
- Android代码规范
- 【leetcode】27. Remove Element
- MyEclipse下JSP代码提示
- 运动目标检测--基于直方图匹配的鬼影消除
- Word Search
- 遇到问题----java----Comparison method violates its general contract异常
- 独特的经历
- 高德地图提示com.autonavi.amap.mapcore.MapCore.nativeNewInstance问题
- 处理问题的思路,基于easyui
- leetcode 263. Ugly Number
- ButterKnife8.0.2的使用例程
- 数据库(一)
- 【HDU】 1788 Chinese remainder theorem again