剑指offer12--矩阵中的路径——java/C++实现

题目描述

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

 

思路:

上下左右处理,最好是调用递归时上下左右,然后进入函数前进行区间判断。这样代码最简洁。参见剑指offer90~91.

回溯:如果处理失败,一定要把相应位的visit清零。

 

class Solution {
public:
    bool hasPathCore(char* matrix,int rows,int cols,char *str,bool* visit,int count,int fx,int fy){
        int len=strlen(str);
        if(count==len) return true;
        int i,j;
        char c=*(str+count);
        bool res=0;
        for(i=0;i<rows;i++)//hang//复杂度比较高,但是代码简单一些。其实应该直接看上下左右的点,然后判断边界
            for(j=0;j<cols;j++)//lie
                if((i==fx-1&&j==fy)||(i==fx+1&&j==fy)||(i==fx&&j==fy+1)||(i==fx&&j==fy-1))
                    if(*(matrix+i*cols+j)==c&&!visit[i*cols+j]){
                        visit[i*cols+j]=1;
                        res=hasPathCore(matrix,rows,cols,str,visit,++count,i,j);
                        if(res)
                            return true;
                        else{
                            visit[i*cols+j]=0;//体现回溯
                            --count;
                        }
                    }
        return false;
    }

    bool hasPath(char* matrix, int rows, int cols, char* str){
        int len=strlen(str);
        bool* visit=new bool[rows*cols];
        int n=sizeof(visit);
        memset(visit,0,rows*cols);
        int i,j;
        char c=*str;
        bool res=0;
        for(i=0;i<rows;i++)//hang
            for(j=0;j<cols;j++)//lie
                if(*(matrix+i*cols+j)==c&&!visit[i*cols+j])
                {
                    visit[i*cols+j]=1;
                    res=hasPathCore(matrix,rows,cols,str,visit,1,i,j);
                    if(res)
                        return true;
                    else
                        visit[i*cols+j]=0;//体现回溯
                }
        return false;
    }
};

 

调试代码:

#include <iostream>

using namespace std;

bool hasPathCore(char* matrix,int rows,int cols,char *str,bool* visit,int count,int fx,int fy){
	int len=strlen(str);
	if(count==len) return true;
	int i,j;
	char c=*(str+count);
	bool res=0;
	for(i=0;i<rows;i++)//hang//复杂度比较高,但是代码简单一些。其实应该直接看上下左右的点,然后判断边界
		for(j=0;j<cols;j++)//lie
			if((i==fx-1&&j==fy)||(i==fx+1&&j==fy)||(i==fx&&j==fy+1)||(i==fx&&j==fy-1))
				if(*(matrix+i*cols+j)==c&&!visit[i*cols+j]){
					visit[i*cols+j]=1;
					res=hasPathCore(matrix,rows,cols,str,visit,++count,i,j);
					if(res)
						return true;
					else{
						visit[i*cols+j]=0;//体现回溯
						--count;
					}
				}
	return false;
}

bool hasPath(char* matrix, int rows, int cols, char* str){
	int len=strlen(str);
	bool* visit=new bool[rows*cols];
	int n=sizeof(visit);
	memset(visit,0,rows*cols);
	int i,j;
	char c=*str;
	bool res=0;
	for(i=0;i<rows;i++)//hang
		for(j=0;j<cols;j++)//lie
			if(*(matrix+i*cols+j)==c&&!visit[i*cols+j])
			{
				visit[i*cols+j]=1;
				res=hasPathCore(matrix,rows,cols,str,visit,1,i,j);
				if(res)
					return true;
				else
					visit[i*cols+j]=0;//体现回溯
			}
	return false;
}

int main ()
{
	char *matrx="ABCEHJIGSFCSLOPQADEEMNOEADIDEJFMVCEIFGGS";
	int a=5,b=8;
	char *str="SLHECCEIDEJFGGFIE";

	int res=hasPath(matrx,a,b,str);
	cout<<res<<endl;
	return 0;

}
public class dfs {

    boolean[][] visit;

    public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
        visit = new boolean[rows][cols];
        char[][] array = new char[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                array[i][j] = matrix[i * cols + j];
            }
        }
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (dfs(array, rows, cols, str, i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] array, int rows, int cols, char[] str, int i, int j, int length) {
        if (length >= str.length) {
            return true;
        }
        if ( i < 0 || i >= rows || j < 0 || j >= cols || visit[i][j] == true || array[i][j] != str[length]) {
            return false;
        }


        visit[i][j] = true;
        boolean isSuccess =
                dfs(array, rows, cols, str, i - 1, j, length + 1)
                        || dfs(array, rows, cols, str, i + 1, j, length + 1)
                        || dfs(array, rows, cols, str, i, j - 1, length + 1)
                        || dfs(array, rows, cols, str, i, j + 1, length + 1);
        visit[i][j] = false;
        return isSuccess;
    }

    public static void main(String[] args) {
        dfs a = new dfs();

        System.out.println(a.hasPath( "ABCESFCSADEE".toCharArray(),3,4,"ABCB".toCharArray()));
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值