【矩阵】【回溯法】矩阵中的路径

题目描述

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

import java.lang.*;
import java.util.*;

public class Solution {
    private static int rows = 0;
    private static int cols = 0;
    public boolean hasPath(char[] matrix, int r, int c, char[] str){
        if(str == null || str.length ==0){
            return true;
        }
        if(null == matrix || r == 0 || c == 0){
            return false;
        }
        
        rows = r;
        cols = c;
        Set<Integer> path = new HashSet<Integer>();
        for(int i = 0; i < matrix.length; i++){
            if(hasPath(matrix, i, str, 0, path)){
                return true;
            }
        }
        return false;
    }
    
    private boolean hasPath(char[] matrix, int offset, char[] strs, int index, Set<Integer> path){
        if(index == strs.length){
            return true;
        }
        if(offset < 0 || offset >= matrix.length || index >= strs.length || matrix[offset] != strs[index] || path.contains(offset)){
            return false;
        }
        
       
            path.add(offset);
        boolean result = hasPath(matrix, offset - 1, strs, index + 1, path) 
            || hasPath(matrix, offset + 1, strs, index + 1, path)
            || hasPath(matrix, offset - cols, strs, index + 1, path)
            || hasPath(matrix, offset + cols, strs, index + 1, path);
            path.remove(offset);
        return result;
    }


}

猜你喜欢

转载自blog.csdn.net/chenxuegui123/article/details/89223791