Nearest Exit from Entrance in Maze
You are given an m x n matrix maze (0-indexed) with empty cells (represented as ‘.’) and walls (represented as ‘+’). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.
In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit.
Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.
Use BFS from the entrance and stop when we get to the exit
Mark visited locations with + to avoid visited them again if modifying input maze is an option
Spiral matrix
Given an m x n matrix, return all elements of the matrix in spiral order.
Edge case: check if firstRow and lastRow, and firstColumn and lastColumn is same in some loop (can happen if matrix is a rectangle)
List<Integer> result = new ArrayList<>();
if (matrix==null || matrix.length==0 || matrix[0].length==0) return result;
for(int rowFirst=0, rowLast=matrix.length-1, columnFirst=0, columnLast=matrix[0].length-1;
rowFirst<=rowLast && columnFirst <= columnLast; rowFirst++, columnFirst++, rowLast--, columnLast--) {
for(int row=rowFirst, column=columnFirst; column<=columnLast; column++) {
result.add(matrix[row][column]);
}
for(int row=rowFirst+1, column=columnLast; row<=rowLast; row++) {
result.add(matrix[row][column]);
}
if (rowFirst!=rowLast) {
for(int row=rowLast, column=columnLast-1; column>=columnFirst; column--) {
result.add(matrix[row][column]);
}
}
if (columnFirst!=columnLast) {
for(int row=rowLast-1, column=columnFirst; row>rowFirst; row--) {
result.add(matrix[row][column]);
}
}
}
return result;