Interview Question - number of friends

题目就是Group of Friends.给一个matrix:
如果 matrix[i][j]=1说明 i knows j,然后问有多少个group. 比如:. 涓€浜�-涓夊垎-鍦帮紝鐙鍙戝竷
{1,1,0,0}
{1,1,1,0}
{0,1,1,0}
{0,0,0,1}
输出就是2
follow up:要求分别输出每个group
BFS解决的这道题。

http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=202672&highlight=snapchat

My code:

public int numOfGroup(char[][] board) {
    if (board == null || board.length == 0 || board[0].length == 0) {
        return 0;
    }
    
    int num = 0;
    for (int i = 0; i < board.length; i++) {
        for (int j = 0; j < board[0].length; j++) {
            if (board[i][j] == '1') {
                dfs(i, j, board);
                num++;
            }
        }
    }
    
    return num;
}

private void dfs(int i, int j, char[][] board) {
    board[i][j] = '0';
    for (int k = i + 1; k < board.length; k++) {
        if (board[k][j] == '1') {
            dfs(k, j, board);
        }
    }
    for (int k = j + 1; k < board[0].length; k++) {
        if (board[i][k] == '1') {
            dfs(i, k, board);
        }
    }
}

follow up, 要求输出每个group。
那我就 最上层 for - loop 里面,每次加入一个List进去。

Anyway, Good luck, Richardo! -- 09/28/2016

你可能感兴趣的:(Interview Question - number of friends)