码迷,mamicode.com
首页 > 其他好文 > 详细

剑指Offer12. 矩阵中的路径

时间:2020-12-03 12:21:11      阅读:6      评论:0      收藏:0      [点我收藏+]

标签:false   solution   iss   problems   oar   题目   bsp   pre   code   

题目:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/submissions/

代码:

class Solution {
    public boolean exist(char[][] board, String word) {
        for(int i=0; i<board.length; i++){
            for(int j=0; j<board[i].length; j++){
                if(board[i][j] == word.charAt(0) && search(board, word, 0, i, j)){
                    return true;
                }
            }
        }
        return false;
    }

    private boolean search(char[][] board, String word, int index, int x, int y){
        if(index >= word.length()) {
            return true;
        }
        if(x < 0 || x >= board.length || y < 0 || y >= board[0].length){
            return false;
        }
        if(board[x][y] != word.charAt(index)){
            return false;
        }
        if(board[x][y] == ‘\0‘){
            return false;
        }
        board[x][y] = ‘\0‘;
        boolean res = search(board, word, index + 1, x+1, y) ||
        search(board, word, index + 1, x-1, y) ||
        search(board, word, index + 1, x, y+1) ||
        search(board, word, index + 1, x, y-1);
        board[x][y] = word.charAt(index);
        return res; 
    } 
}

 

剑指Offer12. 矩阵中的路径

标签:false   solution   iss   problems   oar   题目   bsp   pre   code   

原文地址:https://www.cnblogs.com/liuyongyu/p/14056308.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!