编程题_剑指offer12_矩阵中的路径

1 题目

leetcode
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用加粗标出)。

[[“a”,“b”,“c”,“e”],
[“s”,“f”,“c”,“s”],
[“a”,“d”,“e”,“e”]]

但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。

简而言之,就是在一个二维数组中从任意点出发,沿着四个方向找,不可以访问已经找到的字符,如果找到了就返回true,找不到就返回false

2 解

这一题做了很久,一开始是使用while循环和数组存储已访问的下标,因为解答出错优化了循环逻辑,超出时间限制改用两个Map存储下标,最终还是超出时间限制,看了题解以后发现可以直接使用for循环嵌套,终于是顺利通过了。
移动时先进行判断,防止越界。
map中查找的时候不可以直接使用 containsValue,需要遍历然后确保是同一位置的行和列才行。

    public boolean exist(char[][] board, String word) {
    	//已访问的行下标
		Map<Integer, Integer> rolMap = new HashMap<Integer, Integer>();
		//已访问的列下标
		Map<Integer, Integer> colMap = new HashMap<>();
		//遍历寻找
		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < board[i].length; j++) {
				if (recursive(board, i, j, word, 0, rolMap, colMap)) {
					//找到了
					return true;
				}
			}
		}
		//找不到
		return false;
    }
    private boolean recursive(char[][] board, int boardRow, int boardCol, String word, int wordIndex,
			Map<Integer, Integer> rolMap, Map<Integer, Integer> colMap) {
		if (wordIndex > word.length() - 1) {
			// 找出的字符比目标字符串长
			return true;
		} else {
			// 接着找
			if (board[boardRow][boardCol] == word.charAt(wordIndex)) {
                // 先判断已找到的长度是否和所需长度相同
				if (wordIndex == word.length() - 1) {
					return true;
				}
				// 是要找的字符 放入已访问
				rolMap.put(wordIndex, boardRow);
				colMap.put(wordIndex, boardCol);
				// 向四方查找
				// 上 
				if (boardRow - 1 >= 0 || board[boardRow].length < boardCol) {
					boolean isVisited = false;
					// 是否同一处下标  
					for (int i = 0; i <= wordIndex; i++) {
						if (rolMap.get(i) == boardRow - 1 && colMap.get(i) == boardCol) {
							isVisited = true;
						}
					}
					// 是否已访问
					if (!isVisited) {
						// 未访问 接着找
						if (recursive(board, boardRow - 1, boardCol, word, wordIndex + 1, rolMap, colMap))
							// 找到了
							return true;
					}
				}
				// 左
				if (boardCol - 1 >= 0) {
					boolean isVisited = false;
					// 是否同一处下标
					for (int i = 0; i <= wordIndex; i++) {
						if (rolMap.get(i) == boardRow && colMap.get(i) == boardCol - 1) {
							isVisited = true;
						}
					}
					// 是否已访问
					if (!isVisited) {
						// 未访问 接着找
						if (recursive(board, boardRow, boardCol - 1, word, wordIndex + 1, rolMap, colMap))
							// 找到了
							return true;
					}
				}
				// 下
				if (boardRow + 1 < board.length || board[boardRow].length < boardCol) {
					boolean isVisited = false;
					// 是否同一处下标
					for (int i = 0; i <= wordIndex; i++) {
						if (rolMap.get(i) == boardRow + 1 && colMap.get(i) == boardCol) {
							isVisited = true;
						}
					}
					// 是否已访问
					if (!isVisited) {
						// 未访问 接着找
						if (recursive(board, boardRow + 1, boardCol, word, wordIndex + 1, rolMap, colMap))
							// 找到了
							return true;
					}
				}
				// 右
				if (board[boardRow].length > boardCol + 1) {
					boolean isVisited = false;
					// 是否同一处下标
					for (int i = 0; i <= wordIndex; i++) {
						if (rolMap.get(i) == boardRow && colMap.get(i) == boardCol + 1) {
							isVisited = true;
						}
					}
					// 是否已访问
					if (!isVisited) {
						// 未访问 接着找
						if (recursive(board, boardRow, boardCol + 1, word, wordIndex + 1, rolMap, colMap))
							// 找到了
							return true;
					}
				}
				// 未找到 取出已访问并返回false;
				rolMap.remove(wordIndex);
				colMap.remove(wordIndex);
				return false;

			} else
				// 不是要找的字符 直接返回 false
				return false;
		}
	}

3 题解

题解可以说是相当简洁了,使用char型数组来存储,直接按下标访问;将越界判断放在方法头,调用时可以放心调用;对已访问的字符进行修改,省去了存储已访问位置的空间。我要学习的还很多。

    public boolean exist(char[][] board, String word) {
        char[] words = word.toCharArray();
        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < board[0].length; j++) {
                if(dfs(board, words, i, j, 0)) return true;
            }
        }
        return false;
    }
    boolean dfs(char[][] board, char[] word, int i, int j, int k) {
        if(i >= board.length || i < 0 || j >= board[0].length || j < 0 || board[i][j] != word[k]) return false;
        if(k == word.length - 1) return true;
        char tmp = board[i][j];
        board[i][j] = '/';
        boolean res = dfs(board, word, i + 1, j, k + 1) || dfs(board, word, i - 1, j, k + 1) || 
                      dfs(board, word, i, j + 1, k + 1) || dfs(board, word, i , j - 1, k + 1);
        board[i][j] = tmp;
        return res;
    }

作者:jyd
链接:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/solution/mian-shi-ti-12-ju-zhen-zhong-de-lu-jing-shen-du-yo/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

4 参考链接

1.精选解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值