java - Find available "number" in a 2d array -
i have problem need solve in effecient way. have 2d array contains following: 1 "wall" means cannot go through it. 2 entrance "enter" array or map if like. 3 things need find. here example of map:
1111111 1 3131 2 11111 1 31 1111111
this example of array need in. can see there 3 "unreachable, since it's surrounded wall "1". means there 2 available numbers in array.
first need find entrance. since entrance can anywhere need search entire array. have done following:
int treasureamount = 0; point entrance = new point(0,0); (int = 0; < n; i++) { (int j = 0; j < n; i++){ if(map[i][j] == 2){ entrance.x =i; entrance.y =j; } }
this takes o(n^2) time, , don't see way this, since entrance can anywhere. i'm not sure how find available numbers effectivly , fast. thought while searching arrays entrance @ same time find number 3 in array though might not accessible, , after i'm not sure how effectivly find accessible.
you cannot better o(n^2). take time read array. depth first search find reachable 3's in array. here pseudo code.
main() { read array , mark entrance ent.x , ent.y , array threex[] , threey[] stores exit position. boolean visited[][]; //stores whether array[i][j] reachable or not. dfs(ent.x,ent.y); each element in 3 arrays { if(visited[threex[i]][threey[i]]) print ("reachable"); else print("not reachable", threex[i], threey[i]); } } int dx[]={1,0,-1,0},dy[]={0,1,0,-1}; // dx[i], dy[i] tells whether move in e,n,w,s respectively. dfs(int x,int y) { visited[x][y]=true; for(i=0;i<4;i++)//move in directions { int newx=x+dx[i],newy=y+dy[i]; //check if within array boundary if(newx>=0&&newx<n && newy>=0&&newy<n) if(!visited[newx][newy] && array[newx][newy]!=1) // check if node unvisited , pemissible dfs(newx,newy); } }
since each array element taken not more once in dfs function complexity of code o(n^2).