Is there somebody can tell me why my code is wrong.


  • 0
    H

    void getDirPos(int* x, int* y, int dir)
    {
    switch (dir)
    {
    case 0: //up
    *x = *x;
    *y += 1;
    break;

    	case 1: //right
    		*x += 1;
    		*y = *y;
    		break;
    
    	case 2: //down
    		*x = *x;
    		*y -= 1;
    		break;
    
    	case 3: //left
    		*x -= 1;
    		*y = *y;
    		break;
    
    	default:
    		*x = -1;
    		*y = -1;
    		break;
    }
    
    return;
    

    }

    void dfs(int x, int y, char** grid, int gridRowSize, int gridColSize)
    {
    int dir;

    if (x < 0 || x >= gridRowSize)
    {
    	return;
    }
    
    if (y < 0 || y >= gridColSize)
    {
    	return;
    }
    
    if ('1' != grid[x][y])
    {
    	return;
    }
    
    grid[x][y] = '2';
    /* search 4 direction */
    for (dir=0; dir<4; dir++)
    {
    	getDirPos(&x, &y, dir);
    
    	dfs(x, y, grid, gridRowSize, gridColSize);
    }
    
    return;
    

    }

    int numIslands(char** grid, int gridRowSize, int gridColSize)
    {
    int treeCnt = 0;
    int i, j;

    if (NULL == grid || NULL == *grid)
    {
    	return 0;
    }
    if (gridRowSize < 0 || gridColSize < 0)
    {
    	return 0;
    }
    
    for (i=0; i<gridRowSize; i++)
    {
    	for (j=0; j<gridColSize; j++)
    	{
    		if (grid[i][j] == '1')
    		{
    			treeCnt++;
    
    			dfs(i, j, grid, gridRowSize, gridColSize);
    		}
    	}
    }
    
    return treeCnt;
    

    }


Log in to reply
 

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