首页 > 其他 > 详细

leetcode 079 word search

时间:2016-05-07 09:03:27      阅读:247      评论:0      收藏:0      [点我收藏+]


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 =

[
  [‘A‘,‘B‘,‘C‘,‘E‘],
  [‘S‘,‘F‘,‘C‘,‘S‘],
  [‘A‘,‘D‘,‘E‘,‘E‘]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

Subscribe to see which companies asked this question


class Solution {
public:
   bool find(vector<vector<char>> &board, vector<vector<int>> &visited, string word, int row, int col, int cnt, int used) {
		int rows = board.size(), cols = board[0].size();

		if(cnt==word.length()) return true;
		if(row >= rows || col >= cols || row < 0 || col < 0) return false;
		if(visited[row][col] == 1) return false;
		if(board[row][col]!=word[cnt]) return false;
        
        if(used >= rows*cols) return false;
		visited[row][col] = 1;
		used += 1;
		//cout << "row="<<row<<" col=" << col << board[row][col] << endl;
		bool flag1=find(board, visited, word, row+1, col, cnt+1, used);
		if(flag1) return true;
		bool flag2=find(board, visited, word, row, col+1, cnt+1, used);
		if(flag2) return true;
		bool flag3=find(board, visited, word, row-1, col, cnt+1, used);
		if(flag3) return true;
		bool flag4=find(board, visited, word, row, col-1, cnt+1, used);
        if(flag4) return true;
        
        visited[row][col]=0;
        used-=1;
		return false;
		
	}
	bool exist(vector<vector<char>> &board, string word) {
		int rows=board.size(), cols=0, len=word.length();

		if(rows==0) return false;
        if(len==0) return true;
        
		cols = board[0].size();
        bool ret = false;
        vector<vector<int>> visited(rows, vector<int>(cols,0));
		for(int i=0; i < rows; i++) {
		    for(int j=0; j < cols; j++) {
		        if(board[i][j]==word[0]) {
		            ret = find(board, visited, word, i, j, 0, 0);
		            if(ret==true) return true;
		        }
		    }
		}
		
		return false;
	}
};




leetcode 079 word search

原文:http://blog.csdn.net/suichen1/article/details/51335422

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!