# 79 Word Search

Description

Given an m x n grid of characters board and a string word, return true if word exists in the grid.

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

Note: There will be some test cases with a board or a word larger than constraints to test if your solution is using pruning.

Examples

Example 1:
在这里插入图片描述

Input: board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCCED”
Output: true

Example 2:
在这里插入图片描述

Input: board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “SEE”
Output: true

Example 3:
在这里插入图片描述

Input: board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCB”
Output: false

Constraints:

m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board and word consists of only lowercase and uppercase English letters.

解题思路

这个也没啥说的,就是深搜

代码

class Solution {
    public boolean process(char[][] board, String word, int pos, int row, int col){
        if (pos == word.length()) {
            return true;
        }
        int max_row = board.length;
        int max_col = board[0].length;
        
        if(row < 0 || row >= max_row || col < 0 || col >= max_col || board[row][col] != word.charAt(pos)){
            return false;
        }
        
        board[row][col] = ' ';
        
        if(process(board, word, pos + 1, row, col + 1)){
            return true;
        }
        if(process(board, word, pos + 1, row, col - 1)){
            return true;
        }
        if(process(board, word, pos + 1, row + 1, col)){
            return true;
        }
        if(process(board, word, pos + 1, row - 1, col)){
            return true;
        }
        
        board[row][col] = word.charAt(pos);
        return false;
    }
    public boolean exist(char[][] board, String word) {
        for (int i = 0; i < board.length; i++){
            for (int j = 0; j < board[0].length; j++){
                if(process(board, word, 0, i, j)){
                    return true;
                }
            }
        }
        return false;
    }
}

随笔

有点好玩的是我这份跑下来lc上耗时62ms,但是从他的accept solution里面扒下来一个5ms的代码跑一下也要63ms,所以这个跑的时间是不是不仅仅和算法效率挂钩啊。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值