演算法訓練 Friend Circles

2021-08-02 10:01:05 字數 1436 閱讀 2639

朋友圈:

如果a和b是好朋友,b和c是好朋友,則a、b、c屬於乙個朋友圈。

現用乙個二維矩陣m來記錄n個人的關係,m[i][i]=1,如果 i 和 j 是好友,m[i][j]=1,否則等於0。

題目要求求n個人組成的朋友圈的數目。

example 1:

input: 

[[1,1,0],

[1,1,1],

[0,1,1]]

output: 1

explanation:the 0th and 1st students are direct friends, the 1st and 2nd students are direct friends,

so the 0th and 2nd students are indirect friends. all of them are in the same friend circle, so return 1.

example 2:
input: 

[[1,1,0],

[1,1,0],

[0,0,1]]

output: 2

explanation:the 0th and 1st students are direct friends, so they are in a friend circle.

the 2nd student himself is in a friend circle. so return 2.

dfs:對乙個人i,遍歷其好友,然後在遍歷其好友的好友,這樣可以遍歷出一條朋友圈,朋友圈數加1。在遍歷的時候用乙個數

組標記已訪問過的人,在一條朋友圈訪問結束後,再對未訪問過的人進行同樣的操作,直到所有的人已經訪問結束。

bfs:對乙個人i,遍歷所有其未被訪問過的好友,用乙個佇列來記錄下這些好友,當i的所有的好友訪問結束後,我們再從佇列中

取出乙個好友,進行同樣的操作,當隊列為空的時候,朋友圈數加1。再對未訪問過的人進行同樣的操作,直到所有的人

已經訪問結束。

//dfs

void visitnext(vector>& m, int curpoint, vector& visited)

}int findcirclenum(vector>& m) {

int row=m.size();

int col=m[0].size();

if(row==0) return 0;

int circlenum=0;

vectorvisited(row,0);

for(int i=0;i

your input

[[1,1,0,0],[1,1,0,1],[1,0,1,1],[0,1,1,1]]

your answer

1

expected answer

1

DL RBM訓練演算法

在學習hinton的stack autoencoder演算法 reducing the dimensionality of data with neural networks 之前需要了解什麼是rbm,現在就我學習的情況,查詢的資料 大部分來自部落格 簡單介紹一下rbm。當然,這裡面還有同組實驗的同...

演算法訓練 C Calculations

問題描述 c 語言和c 語言非常相似,然而c 的程式有時會出現意想不到的結果。比如像這樣的算術表示式 表示式 基本式 表示式 基本式 表示式 基本式 基本式 增量 係數 增量 增量 a a 係數 0 1 2 1000 如 5 a 3 a a 是合法的c 表示式。計算這樣的表示式的值的方法 首先是每個...

演算法訓練 暗戀

演算法訓練 暗戀 時間限制 1.0s 記憶體限制 256.0mb 問題描述 同在乙個高中,他卻不敢去找她,雖然在別人看來,那是再簡單不過的事。暗戀,是他唯一能做的事。他只能在每天課間操的時候,望望她的位置,看看她傾心的動作,就夠了。操場上的彩磚啊,你們的位置,就是他們能夠站立的地方,他倆的關係就像磚...