Apologies if it sounds too illogical.
While solving some of the competitive questions today, a weird thought came across my mind.
We say time complexity of DFS is O(V+E) because we traverse the adjacency list only once i.e for every node we consider its edges.
However when performing dfs on matrix of size MN. A matrix we can say, is a graph with MN vertices (every cell is a vertex) and there is an edge to its neighbouring cell ==> every vertex have 4 edges (lets ignore border cases for simplicity)
Then while we do DFS
private void dfs(int grid[][], int i, int j, int m, int n) {
if(i<0 || j<0 || i>m || j>n || visited[i][j])
return;
visited[i][j] = true;
dfs(grid, i+1, j, m, n);
dfs(grid, i-1, j, m, n);
dfs(grid, i, j-1, m, n);
dfs(grid, i, j+1, m, n)
visited[i][j] = false;
}
==> in graph terminology its O(V+E) => O(MN + 4MN) => O(5MN) => O(MN) ==> But time complexity is 4^(MN)
Where does this analogy goes wrong?