还在理解中。。。
leetcode 200. Number of Islands
Input:
11110
11010
11000
00000
Output: 1
vs
leetcode 79. Word Search
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
两题写法非常相似,怎么理解?
The island solution is using DFS:
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int res = 0;
for (int i = 0; i < grid.size(); ++i)
for (int j = 0; j < grid[0].size(); ++j)
if ('1' == grid[i][j])
{
res++;
DFS(grid, i, j);
}
return res;
}
private:
void DFS(vector<vector<char>>&grid, int i, int j)
{
if(grid[i][j] == '1')
{
grid[i][j] = '0';
}
if(i>0 && grid[i-1][j] == '1') DFS(grid,i-1,j);
if(i+1 < grid.size() && grid[i+1][j] == '1') DFS(grid,i+1,j);
if(j>0 && grid[i][j-1] == '1') DFS(grid,i,j-1);
if(j+1 < grid[0].size() && grid[i][j+1] == '1') DFS(grid,i,j+1);
}
};
The word search solution is using backtracking:
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
for(int i = 0; i < board.size(); i++)
{
for(int j = 0; j < board[0].size(); j++)
{
if(helper(board, word, i, j, 0))
{
return true;
}
}
}
return false;
}
bool helper(vector<vector<char>>& board, string word, int i, int j, int index)
{
if(index == word.size())
{
return true;
}
if(i < 0 || j < 0 || i >= board.size() || j >= board[0].size() || board[i][j] == '*' || board[i][j] != word[index])
{
return false;
}
board[i][j] = '*';
bool res = helper(board, word, i-1, j, index + 1) ||
helper(board, word, i, j - 1, index + 1) ||
helper(board, word, i + 1, j, index + 1) ||
helper(board, word, i, j + 1, index + 1);
board[i][j] = word[index];
return res;
}
};