- 01 Matrix
Failed Code:
public class Solution {
int[] xdir = {-1,1,0,0};
int[] ydir = {0,0,-1,1};
int ROW, COL;
boolean[][] visitedOnce;
public List<List<Integer>> updateMatrix(List<List<Integer>> matrix) {
List<List<Integer>> returnList = new ArrayList<List<Integer>>();
ROW = matrix.size();
COL = matrix.iterator().next().size();
//flatten matrix
int[][] ma = new int[ROW][COL];
visitedOnce = new boolean[ROW][COL];
int index = 0;
for(List<Integer> row : matrix)
{
int j = 0;
for(Integer point : row)
{
ma[index][j] = point;
j++;
}
index++;
}
for(int i=0; i<ROW; i++)
{
for(int j=0; j<COL; j++)
{
if(ma[i][j] == 0 && isAroundOne(ma, i, j))
{
bfs(ma, i, j);
}
}
}
//return
for(int i=0; i<ROW; i++)
{
List<Integer> row = new ArrayList<Integer>();
for(int j=0; j<COL; j++)
{
row.add(ma[i][j]);
}
returnList.add(row);
}
return returnList;
}
private boolean isAroundOne(int[][] ma, int i, int j)
{
for(int k=0; k<4; k++)
{
int x = i + xdir[k];
int y = j + ydir[k];
if(inBoundary(x, y) && ma[x][y]!=0)
{
return true;
}
}
return false;
}
private boolean inBoundary(int x, int y)
{
if(x >= 0 && x<ROW && y>=0 && y<COL)
{
return true;
}
return false;
}
private void bfs(int[][] ma, int i, int j)
{
boolean[][] visited = new boolean[ROW][COL];
Deque<Integer> queuex = new LinkedList<Integer>();
Deque<Integer> queuey = new LinkedList<Integer>();
queuex.offer(i);
queuey.offer(j);
while(!queuex.isEmpty())
{
int x = queuex.poll();
int y = queuey.poll();
for(int k = 0; k<4; k++)
{
int xx = x + xdir[k];
int yy = y + ydir[k];
if(inBoundary(xx, yy) && ma[xx][yy]>0 && !visited[xx][yy])
{
if(!visitedOnce[xx][yy])
{
if(ma[xx][yy]!=0)
{
ma[xx][yy] = ma[x][y] + 1;
queuex.offer(xx);
queuey.offer(yy);
visited[xx][yy] = true;
visitedOnce[xx][yy] = true;
}
}
else
{
if(ma[x][y] < ma[xx][yy] - 1)
{
ma[xx][yy] = ma[x][y] + 1;
queuex.offer(xx);
queuey.offer(yy);
visited[xx][yy] = true;
}
}
}
}
}
}
}