题解 | #矩阵中的路径#

矩阵中的路径

https://www.nowcoder.com/practice/2a49359695a544b8939c77358d29b7e6

import java.util.*;

/**
 * NC285 矩阵中的路径
 * @author d3y1
 */
public class Solution {
    private int LEN;
    private boolean isFound = false;
    private int[] dx = new int[]{0, 1, 0, -1};
    private int[] dy = new int[]{1, 0, -1, 0};
    private boolean[][] isVisited;
    private int ROW;
    private int COL;

    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param matrix char字符型二维数组
     * @param word string字符串
     * @return bool布尔型
     */
    public boolean hasPath (char[][] matrix, String word) {
        LEN = word.length();
        ROW = matrix.length;
        COL = matrix[0].length;
        isVisited = new boolean[ROW][COL];

        for(int i = 0; i < ROW; i++){
            for(int j = 0; j < COL; j++){
                if(matrix[i][j] == word.charAt(0)){
                    dfs(matrix, i, j, word, 0);
                }
            }
        }

        return isFound;
    }

    /**
     * dfs
     * @param matrix
     * @param x
     * @param y
     * @param word
     * @param index
     */
    private void dfs(char[][] matrix, int x, int y, String word, int index){
        // 当前字符相同
        if(matrix[x][y] == word.charAt(index)){
            // 找到路径
            if(index+1 == LEN){
                isFound = true;
                return;
            }
            // 未找到路径
            if(!isFound){
                // 下一步坐标
                int nextX,nextY;
                for(int i = 0; i < 4; i++){
                    nextX = x+dx[i];
                    nextY = y+dy[i];
                    // 合法
                    if(isValid(nextX, nextY)){
                        // 未访问过
                        if(!isVisited[nextX][nextY]){
                            // 标记已访问
                            isVisited[nextX][nextY] = true;
                            dfs(matrix, nextX, nextY, word, index+1);
                            // 标记未访问
                            isVisited[nextX][nextY] = false;
                        }
                    }
                }
            }
        }
    }

    /**
     * 是否合法(是否越界)
     * @param x
     * @param y
     * @return
     */
    private boolean isValid(int x, int y){
        if(x<0 || x>=ROW || y<0 || y>=COL){
            return false;
        }

        return true;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-10 14:00
林子大了什么鸟都有啊,我觉得我说的已经很客气了,阴阳谁呢
牛客62656195...:应该不是阴阳吧?你第一次注册的时候boss就说你是牛人
点赞 评论 收藏
分享
06-11 17:39
门头沟学院 Java
小呆呆的大鼻涕:卧槽,用户彻底怒了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务