题解 | #矩阵中的路径#

矩阵中的路径

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

import java.util.*;


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

相关推荐

评论
点赞
收藏
分享

创作者周榜

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