DFS C++


  • 0
    N

    class Solution {
    public:
    void dfs(vector<vector<char>>& board, int i, int j)
    {
    visited[i][j] = true;
    //left
    if (i >= 0 && i < n && j - 1 >= 0 && j - 1 < m && !visited[i][j - 1] && board[i][j - 1] == 'X')
    {
    dfs(board, i, j - 1);
    }
    //right
    if (i >= 0 && i < n && j + 1 >= 0 && j + 1 < m && !visited[i][j + 1] && board[i][j + 1] == 'X')
    {
    dfs(board, i, j + 1);
    }
    //top
    if (i - 1 >= 0 && i - 1 < n && j >= 0 && j < m && !visited[i - 1][j] && board[i - 1][j] == 'X')
    {
    dfs(board, i - 1, j);
    }
    //bottom
    if (i + 1 >= 0 && i + 1 < n && j >= 0 && j < m && !visited[i + 1][j] && board[i + 1][j] == 'X')
    {
    dfs(board, i + 1, j);
    }
    }

    int countBattleships(vector<vector<char>>& board) {
    	n = board.size();
    	m = board[0].size();
    	num = 0;
    	for (int i = 0; i < n; ++i)
    	{
    		for (int j = 0; j < m; ++j)
    		{
    			visited[i][j] = false;
    		}
    	}
    	for (int i = 0; i < n; ++i)
    	{
    		for (int j = 0; j < m; ++j)
    		{
    			if (board[i][j] == 'X' && !visited[i][j])
    			{
    				num++;
    				dfs(board, i, j);
    			}
    		}
    	}
    	return num;
    }
    

    private:
    int n;
    int m;
    int num;
    bool visited[1000][1000];
    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.