百度真题之走迷宫

题目:

给定一个矩阵,元素1表示可走路径,0表示不可走路径,从左上角开始,目标是值为9的坐标点,判断是否有一个路径到达目的地。如:

1 0 0 0 1 0

1 1 0 0 1 0

0 1 1 9 0 0

0 0 0 1 0 0

该矩阵存在到达数值为9的点的路径

 

分析:

 

采用回溯思想

 

代码

import java.io.*;

/**
 * Created by wuchao on 17-4-26.
 */
public class Main2 {
    public static void main(String[] args) throws IOException {
        int[][] maze = {{1,1,0,0,0},
                        {0,1,0,0,0},
                        {0,1,0,1,0},
                        {1,1,0,9,0},
                        {0,1,1,1,1}};
        System.out.print(hasPath(maze));
    }
    public static boolean hasPath(int[][] matrix)
    {
        if(matrix.length<=0) return false;

        //用于记录搜索路径,防止重复,已经搜索过的计为1
        int flag[][] = new int[matrix.length][matrix[0].length];
        //从matrix[0][0]开始搜索
        if(helper(matrix,0,0,flag))
                    return true;
        return false;
    }
    //判断matrix[i][j]是否是重复搜索的点,是否越界,是否是目标点,如果都不是,标记当前点为已搜索的点,并继续搜索周边的点
    //当周边的点都不满足,则将当前点的标记清除,返回false
    public static boolean helper(int[][] matrix,int i,int j,int[][] flag) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        if (i < 0 || i >= rows || j < 0 || j >= cols || matrix[i][j]==0 || flag[i][j] == 1)
            return false;
        if(matrix[i][j]==9) return true;
        flag[i][j]=1;
        if(helper(matrix,i-1,j,flag)
                ||helper(matrix,i+1,j,flag)
                ||helper(matrix,i,j-1,flag)
                ||helper(matrix,i,j+1,flag)
                ){
            return true;
        }
        flag[i][j]=0;
        return false;
    }
}

 

posted @ 2016-09-16 19:56  且听风吟-wuchao  阅读(233)  评论(0)    收藏  举报