# Easy java solution using O(1) space beats 40% of submissions

• class Solution {
public int maxKilledEnemies(char[][] grid) {

//Base case: if grid is empty or null, return 0
if(grid==null || grid.length==0)
return 0;

//General case: if 1 or more elements are present in the grid
int currentSolution=0;
int maxSolution=0;

//for loop to iterate through the grid
for(int i=0;i<grid.length;i++)
{
for(int j=0;j<grid[0].length;j++)
{
//if an element is 0, can place bomb here
if(grid[i][j]=='0')
{

currentSolution=moveLeft(i,j-1,grid)+moveUp(i-1,j,grid)+moveRight(i,j+1,grid)+moveDown(i+1,j,grid);

//update maxSolution if currentSolutio is greater
if(currentSolution>maxSolution)
maxSolution=currentSolution;
}
}
}

return maxSolution;

}

public int moveLeft(int currentRow, int currentColumn,char[][] grid)
{
//Base case:to check if within bounds
if(currentColumn<0)
return 0;

//Case 1: if entry is 0, move left
if(grid[currentRow][currentColumn]=='0')
return moveLeft(currentRow,currentColumn-1,grid);
//Case 2: if entry is E, add 1 and recurse on the left
else if(grid[currentRow][currentColumn]=='E')
return 1+moveLeft(currentRow,currentColumn-1,grid);
//Case 3: if entry is W , return 0
else
return 0;
}

public int moveUp(int currentRow, int currentColumn,char[][] grid)
{
//Base case:check if within bounds
if(currentRow<0)
return 0;

//Case 1: if entry is 0, move up
if(grid[currentRow][currentColumn]=='0')
return moveUp(currentRow-1,currentColumn,grid);
//Case 2: if entry is E, add 1 and recurse on the top
else if(grid[currentRow][currentColumn]=='E')
return 1+moveUp(currentRow-1,currentColumn,grid);
//Case 3: if entry is W , return 0
else
return 0;
}

public int moveRight(int currentRow, int currentColumn,char[][] grid)
{
//Base case: check if within bounds
if(currentColumn>=grid[0].length)
return 0;
//Case 1: if entry is 0, move right
if(grid[currentRow][currentColumn]=='0')
return moveRight(currentRow,currentColumn+1,grid);
//Case 2: if entry is E, add 1 and recurse on the right
else if(grid[currentRow][currentColumn]=='E')
return 1+moveRight(currentRow,currentColumn+1,grid);
//Case 3: if entry is W , return 0
else
return 0;
}

public int moveDown(int currentRow, int currentColumn,char[][] grid)
{
//Base case: check if within bounds
if(currentRow>=grid.length)
return 0;
//Case 1: if entry is 0, move down
if(grid[currentRow][currentColumn]=='0')
return moveDown(currentRow+1,currentColumn,grid);
//Case 2: if entry is E, add 1 and recurse on the bottom
else if(grid[currentRow][currentColumn]=='E')
return 1+moveDown(currentRow+1,currentColumn,grid);
//Case 3: if entry is W , return 0
else
return 0;
}
}

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