题解 | #矩阵中的路径#

矩阵中的路径

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

using System;
using System.Collections.Generic;


class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param matrix char字符型二维数组 
     * @param word string字符串 
     * @return bool布尔型
     */
    public bool hasPath (List<List<char>> matrix, string word) {
        // write code here
        if(matrix.Count == 0)
            return false;
        
        int row = matrix.Count;
        int col = matrix[0].Count;
        List<List<bool>> gridCover = new List<List<bool>>(row);
        for(int i=0;i<row;i++){
            gridCover.Add(new List<bool>(col));
            for(int j=0;j<col;j++){
                gridCover[i].Add(false);
            }
        }
        
        for(int i=0; i<row; i++){
            for(int j=0;j<col;j++){
                if(step(matrix, word, gridCover, i, j, 1)){
                    return true;
                }
            }
        }
        return false;
    }
    
    public bool step(List<List<char>> matrix, string word, List<List<bool>> gridCover, int x, int y, int length){
        if(0 <= x && x < matrix.Count && 0 <= y && y < matrix[0].Count && !gridCover[x][y] && matrix[x][y] == word[length-1]){
            gridCover[x][y] = true;
            if (length == word.Length){
                return true;
            }else if (step(matrix, word, gridCover, x-1, y, length+1)
                || step(matrix, word, gridCover, x+1, y, length+1)
                || step(matrix, word, gridCover, x, y-1, length+1)
                || step(matrix, word, gridCover, x, y+1, length+1)){
                return true;
            }else{
                gridCover[x][y] = false;
                return false;
            }
        }
        return false;
    }
}
全部评论

相关推荐

头像
01-29 18:11
海南大学 Java
奔跑的suechil...:单从项目看这个简历不怕被问穿吗 带微服务的项目需要相当多的项目理解和经验诶
点赞 评论 收藏
分享
2025-12-14 11:43
黑龙江大学 Java
用微笑面对困难:确实比较烂,可以这么修改:加上大学的qs排名,然后大学简介要写一些,然后硕士大学加大加粗,科研经历第一句话都写上在复旦大学时,主要负责xxxx,简历左上角把学校logo写上,建议用复旦大学的简历模板
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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