回溯法以及搜索遍历的方向控制

1,对于方格的回溯遍历

(1)控制方向使用基本方向数组: int[][] next = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};

(2)循环遍历取向:

      for (int[] n : next)
        if (backtracking(matrix, str, marked, pathLen + 1, r + n[0], c + n[1]))
            return true;

其中 n[0]=0,0,-1,1 , n[1]=-1,1,0,0

这意味着每次对于行列只有一个方向是操作的,且同时满足四个方向上的移动(每次一个)。

(3)典型题目解析 剑指offer12:

2, 矩阵中的路径

题目描述:
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。

例如下面的矩阵包含了一条 bfce 路径。
图例

代码如下:


    package come;
    
    /**
     * 矩阵中的路径问题(回溯法)--指定路径
     * @author lzq
     * @version 1.0
     * @description
     * @date 2019/7/31 21:33
     */
    import java.util.*;
    public class Main7 {
    
        private static final int[][] next = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
        private int rows;
        private int cols;
    
        public boolean hasPath(char[] array, int rows, int cols, char[] str)
        {
            if(cols==0||rows==0)
            {
                return false;
            }
    
            this.rows=rows;
            this.cols=cols;
    
            boolean[][] panduan=new boolean[rows][cols];
    
            char[][] news=tochange(array);
    
            for(int i=0;i<rows;i++)
            {
                for(int j=0;j<cols;j++)
                {
                    if(backtrack(news,str,i,j,0,panduan))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
    
        public boolean backtrack(char[][] news,char[] str,int r,int c,int pathlen,boolean[][] panduan)
        {
            if(pathlen==str.length)
            {
                return true;
            }
    
            if(r<0||r>=rows||c<0||c>=cols||news[r][c]!=str[pathlen]||panduan[r][c])
            {
                return false;
            }
            panduan[r][c]=true;
    
            for(int[] n:next)
            {
                if(backtrack(news,str,r+n[0],c+n[1],pathlen+1,panduan))
                {
                    return true;
                }
            }
            panduan[r][c]=false;
    
            return false;
    
        }
        public char[][] tochange(char[] nums)
        {
            char[][] news=new char[rows][cols];
    
            int index=0;
            for(int i=0;i<rows;i++)
            {
                for(int j=0;j<cols;j++)
                {
                    news[i][j]=nums[index++];
                }
            }
    
            return news;
        }
    
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Tronhon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值