标签:exist lazy str rom valueof 一维数组 数组 java 匹配
题目描述
输入输出案例
参考
思路
使用回溯、递归、枚举的思想
代码
class Solution {
public boolean exist(char[][] board, String word) {
//用于标记是否已经被访问的二维数组
boolean[][] isSearched = 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(solve(board,word,i,j,isSearched,0)){
return true;
}
}
}
//执行到此处,返回false
return false;
}
private boolean solve(char[][] board, String word, int i, int j, boolean[][] isSearched, int i1) {
int index = i1;
//递归的退出条件(边界判断)
if(i<0 || i >=board.length || j<0 || j>=board[0].length || isSearched[i][j]){
return false;
}
//匹配到某一位置不满足退出
if(word.charAt(index)!=board[i][j]){
return false;
}
//成功匹配到字符串末尾
if (index==word.length()-1){
return true;
}
//本次访问就把[i,j]位置标志为已访问
isSearched[i][j] = true;
//递归体
boolean flag = solve(board,word,i+1,j,isSearched,index+1) || //注意这里要写index+1 ,不能每个都写index++;
solve(board,word,i-1,j,isSearched,index+1) ||
solve(board,word,i,j-1,isSearched,index+1) ||
solve(board,word,i,j+1,isSearched,index+1);
//访问过程,重新恢复访问标志。(回溯思想)
isSearched[i][j] = false;
return flag;
}
}
牛客的输入格式
Java代码
public class Solution {
public boolean hasPath(char[] matrix, int rows, int cols, char[] str){
//这里把一维数组变为二维数组
char[][] board = new char[rows][cols];
//一维数组转二维
int index = 0;
int row_ = 0;
for(int i=0;i<matrix.length;i++){
if(index>=cols){
index = 0; //索引置为0
row_++;//换下一行
}
board[row_][index] = matrix[i];
index++;
}
//char[] 数组变字符串
String word = String.valueOf(str);
//调用
return exist(board,word);
}
//力扣的输入
public boolean exist(char[][] board, String word) {
//用于标记是否已经被访问的二维数组
boolean[][] isSearched = 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(solve(board,word,i,j,isSearched,0)){
return true;
}
}
}
//执行到此处,返回false
return false;
}
private boolean solve(char[][] board, String word, int i, int j, boolean[][] isSearched, int i1) {
int index = i1;
//递归的退出条件(边界判断)
if(i<0 || i >=board.length || j<0 || j>=board[0].length || isSearched[i][j]){
return false;
}
//匹配到某一位置不满足退出
if(word.charAt(index)!=board[i][j]){
return false;
}
//成功匹配到字符串末尾
if (index==word.length()-1){
return true;
}
//本次访问就把[i,j]位置标志为已访问
isSearched[i][j] = true;
//递归体
boolean flag = solve(board,word,i+1,j,isSearched,index+1) || //注意这里要写index+1 ,不能每个都写index++;
solve(board,word,i-1,j,isSearched,index+1) ||
solve(board,word,i,j-1,isSearched,index+1) ||
solve(board,word,i,j+1,isSearched,index+1);
//访问过程,重新恢复访问标志。(回溯思想)
isSearched[i][j] = false;
return flag;
}
}
标签:exist lazy str rom valueof 一维数组 数组 java 匹配
原文地址:https://www.cnblogs.com/jiyongjia/p/13378536.html