Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public int numIslands(char[][] grid) {
- int[] rowMovement = {-1, 0, 1, 0};
- int[] colMovement = {0, -1, 0, 1};
- int numberOfRows = grid.length;
- int numberOfCols = grid[0].length;
- int row;
- int col;
- int movingRow = 0;
- int movingCol = 0;
- int tempRow = 0;
- int tempCol = 0;
- int count = 0;
- char c;
- Queue<Integer> q = new ArrayDeque<Integer>();
- for (row = 0; row < numberOfRows; row++){
- for (col = 0; col < numberOfCols; col++){
- if (grid[row][col] == '1'){ //if it encounters a 1, increment count. Below changes
- q.add(row);
- q.add(col);
- movingRow = row;
- movingCol = col;
- while(!q.isEmpty()){
- movingRow = q.remove();
- movingCol = q.remove();
- c = grid[movingRow][movingCol];
- grid[movingRow][movingCol] = '9';//indicate you've visited now
- if (c == '1'){
- for (int k = 0; k < 4; k++){
- tempRow = movingRow+rowMovement[k];
- tempCol = movingCol+colMovement[k];
- if (isValid(tempRow, tempCol, numberOfCols, numberOfRows, grid)){
- q.add(tempRow);
- q.add(tempCol);
- }
- }
- }
- }
- count++;
- }
- if (grid[row][col] == '9'){
- //count++;
- continue; //move on in for loop if we've already been here;
- }
- else{
- count++;
- grid[row][col] = '9'; //set to visited as indicated by 9
- }
- }
- }
- return count;
- }
- public boolean isValid(int row, int col, int numberOfCols, int numberOfRows, char[][] grid){
- if ((row < numberOfRows) && (col < numberOfCols) && (row >= 0) && (col >= 0)){
- return true;
- }
- else{
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement