leetcode 079 —— Word Search

来源:互联网 发布:js关闭当前页面并跳转 编辑:程序博客网 时间:2024/05/16 10:38

Given a 2D board and a word, find if the word exists in the grid.

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

For example,
Given board =

[  ["ABCE"],  ["SFCS"],  ["ADEE"]]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

思路: 思路,用一个矩阵记录被使用的单词,但是代码跑了44ms,还有优化的空间

class Solution {public:bool exist(vector<vector<char>>& board, string word) {bool judge = false;int level = 0;vector<vector<bool>> record(board.size(), vector<bool>(board[0].size(), false));for (int m = 0; m <board.size(); m++){for (int n = 0; n <board[0].size(); n++){if (board[m][n] == word[0]){record[m][n] = true;level = 1;scan(m, n, judge, level, word, record, board);if (judge) return judge;record[m][n] = false;}}}return judge;}void scan(int i, int j, bool &judge,int &level, string &word,vector<vector<bool>> &record,vector<vector<char>> &board){if (level== word.size()){judge = true;return;}if (i + 1 < board.size() && !record[i + 1][j] && board[i + 1][j] == word[level]){  //往右  record[i + 1][j] = true;level++;scan(i + 1, j, judge, level, word, record, board);level--;if (judge) return;record[i + 1][j] = false;}if (i - 1 >= 0 && !record[i - 1][j] && board[i - 1][j] == word[level]){//往左record[i - 1][j] = true;level++;scan(i - 1, j, judge, level, word, record, board);level--;if (judge) return;record[i - 1][j] = false;}if (j + 1 < board[0].size() && !record[i][j + 1] && board[i][j+1] == word[level]){//往下record[i][j+1] = true;level++;scan(i, j + 1, judge, level, word, record, board);level--;if (judge) return;record[i][j+1] = false;}if (j - 1 >= 0 && !record[i][j - 1] && board[i][j-1] == word[level]){//往上record[i][j-1] = true;level++;scan(i , j-1, judge, level, word, record, board);if (judge) return;level--;record[i][j-1] = false;}}};


0 0
原创粉丝点击